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.
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:
if awk '$0 ~ p { gsub(p, r); t=1} 1 END{ exit (!t) }' p="$pattern" r="$repl" "$filename" > "${filename}.new"; then cat "${filename}.new" > "${filename}" # DO SOME OTHER STUFF HERE else # DO SOME OTHER STUFF HERE fi
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.