I am trying to find a clever way to figure out if the file passed to sed has been altered successfully or not.
Basically, I want to know if the file has been changed or not without having to look at the file modification date.
The reason why I need this is because I need to do some extra stuff if sed has successfully replaced a pattern.
I currently have:
grep -q $pattern $filename if [ $? -eq 0 ] then sed -i s:$pattern:$new_pattern: $filename # DO SOME OTHER STUFF HERE else # DO SOME OTHER STUFF HERE fi
The above code is a bit expensive and I would love to be able to use some hacks here.
You can use the stat command on a file to check access and modification times or set up RCS to track changes. You can use MD5 or sum to get the current state of the file, copy that value to a file and then that file to verify that the original file wasn't changed.
By default sed does not overwrite the original file; it writes to stdout (hence the result can be redirected using the shell operator > as you showed).
Note that sed doesn't alter the original file, so all changes will show in the output, but the original file remains the same for each command we successively run.
A bit late to the party but for the benefit of others, I found the 'w' flag to be exactly what I was looking for.
sed -i "s/$pattern/$new_pattern/w changelog.txt" "$filename" if [ -s changelog.txt ]; then # CHANGES MADE, DO SOME STUFF HERE else # NO CHANGES MADE, DO SOME OTHER STUFF HERE fi
changelog.txt
will contain each change (ie the changed text) on it's own line. If there were no changes, changelog.txt
will be zero bytes.
A really helpful sed resource (and where I found this info) is http://www.grymoire.com/Unix/Sed.html.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With