Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if sed has changed a file

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.

like image 762
breakdown1986 Avatar asked Aug 27 '12 14:08

breakdown1986


People also ask

How can you tell if a file has been changed?

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.

Does sed overwrite file?

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).

Does sed command change the original file?

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.


1 Answers

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.

like image 119
aureliandevel Avatar answered Sep 28 '22 06:09

aureliandevel