Riaan's SysAdmin Blog

My tips, howtos, gotchas, snippets and stuff. Use at your own risk!

Bash

bash-scan-text-block-reverse

example finding a block.

start string and reverse search up to next string. then replacing a line inside the block

bash example

$ cat listener-update.sh 
#!/bin/bash
#v0.9.1
file="listener_test.yml"
dir="./unregister"
variable="bar"

codeuri_num=$(grep -n "CodeUri: $dir" $file | awk '{print $1}' FS=":")
function_num=$(grep -n "Type: 'AWS::Serverless::Function'" $file | awk '{print $1}' FS=":")
block=$(sed "${function_num},${codeuri_num}!d" $file)

echo
if [[ "$block" == *"AutoPublishCodeSha256"* ]];then
  echo "found AutoPublishCodeSha256 so update"
  line=$(echo "${block}" | grep -n "AutoPublishCodeSha256")
  line_num=$(awk "/Auto/ && NR >= ${function_num} && NR <= ${codeuri_num} {print NR}" $file)
  newline="AutoPublishCodeSha256: $var"
  sed -i "${line_num}s/.*/ \ \ \ \ \ AutoPublishCodeSha256: $variable/" $file
else
  echo "AutoPublishCodeSha256 not found so insert"
  #codeuri_num=$((codeuri_num+1))
  sed -i "${codeuri_num} i \ \ \ \ \ \ AutoPublishCodeSha256: $variable" $file
fi

admin

Bio Info for Riaan