Skip to content
Advertisement

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:

JavaScript

The above code is a bit expensive and I would love to be able to use some hacks here.

Advertisement

Answer

You could use awk instead:

awk '$0 ~ p { gsub(p, r); t=1} 1 END{ exit (!t) }' p="$pattern" r="$repl

I’m ignoring the -i feature: you can use the shell do do redirections as necessary.

Sigh. Many comments below asking for basic tutorial on the shell. You can use the above command as follows:

JavaScript

It is not clear to me if “DO SOME OTHER STUFF HERE” is the same in each case. Any similar code in the two blocks should be refactored accordingly.

Advertisement