Skip to content

Instantly share code, notes, and snippets.

@apolopena
Created March 27, 2022 18:30
Show Gist options
  • Save apolopena/18f96023799e6a86b84d0a263cadd03e to your computer and use it in GitHub Desktop.
Save apolopena/18f96023799e6a86b84d0a263cadd03e to your computer and use it in GitHub Desktop.
search and replace (parse) a line of code in a file with `sed` and know if sed actually made any changes

The Need

You need to search and replace (parse) a line of code in a file with sed and know if sed actually made any changes

The Solution

sed can save its output to a backup file if you append the file extension to the -i option. You can then used cmp silently to check if the files have changed. cmp checks the bytes of the files so the comparison is not processor intensive. Finally just remove the backup file and there is no mess left behind.

Examples

Simple in place replacement in the file myfile.txt and confirm if changes were made

'sed -i.bak '/TEXT_TO_BE_REPLACED/c\This is the next text.' myfile.txt
if cmp -s "myfile.txt" "myfile.txt.bak"; then
  echo "$myfile.txt did not change"
else
  echo "myfile.txt changed"
fi
rm "myfile.txt.bak"

Replace a line of code with new code in the file myfile.txt and confirm if changes were made. The new code is stored in a variable, beware of quote usage here. Note that the code to be replaced must have all special characters escaped, for example $ becomes \$. For the sake of berevity we will store the file we are trying to parse in the variable $file

file="myfile.txt"
new_code='tools_dir=$(dirname -- "$(readlink -f -- "${BASH_SOURCE[0]}")")/.glstools'
sed -i.bak "/^tools_dir=\$(dirname/c $new_code" "$file"
if cmp -s "$file" "$file.bak"; then
  echo "$file did not change"
else
  echo "$file changed"
fi
rm "$file.bak"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment