This question already has an answer here:
- How to check if sed has changed a file 6 answers
This command replaces the old string with the new one if the one exists.
sed "s/$OLD/$NEW/g" "$source_filename" > $dest_filename
How can I check if the replacement happened ? (or how many times happened ?)
sed is not the right tool if you need to count the substitution, awk will fit better your needs :
This latest solution counts only the number of lines substituted. The next snippet counts all substitutions with perl. This one has the advantage to be clearer than
awk
and we keep the syntax ofsed
substitution :Edit
Thanks to william who had found the
$count += s///g
trick to count the number of substitutions (even or not on the same line)If it is free for you to choose other tool, like awk, (as @sputnick suggested), go with other tools. Awk could count how many times the pattern matched.
sed itself cannot count replacement, particularly if you use
/g
flag. however if you want to stick tosed
and know the replacement times there is possibilities:One way is
you could also do it with tee
see this small example:
This
awk
should count the total number of substitutions instead of the number of lines where substitutions took place:this worked for me.