Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the sed command replaced some string? [duplicate]

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

like image 794
Lukap Avatar asked Mar 15 '13 12:03

Lukap


People also ask

How do you use sed command to replace a string in a file?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

Which sed command is used for replacement?

Replacing all the occurrence of the pattern in a line : The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line. Output : linux is great os.


1 Answers

sed is not the right tool if you need to count the substitution, awk will fit better your needs :

awk -v OLD=foo -v NEW=bar '
    ($0 ~ OLD) {gsub(OLD, NEW); count++}1
    END{print count " substitutions occured."}
' "$source_filename"

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 of sed substitution :

OLD=foo NEW=bar perl -pe '
    $count += s/$ENV{OLD}/$ENV{NEW}/g;
    END{print "$count substitutions occured.\n"}
' "$source_filename"

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)

like image 173
Gilles Quenot Avatar answered Oct 06 '22 22:10

Gilles Quenot