该命令替换旧的字符串,如果存在一个新的。
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的是不正确的工具,如果你需要计算的替代,的 AWK 会更符合您的需要:
sed is not the right tool if you need to count the substitution, awk will fits better your needs :
awk -v OLD=foo -v NEW=bar ' ($0 ~ OLD) {gsub(OLD, NEW); count++}1 END{print count " substitutions occured."} ' "$source_filename"这最新的解决方案只计数取代的行数。接下来的片段数与 perl的。这其中的优势比 AWK 更清晰,我们不断的语法 SED 替换:
This latest solution count only the number of lines substituted. The next snippet count all substitutions with perl. This one have 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"修改
感谢威廉谁找到了 $计数+ = S /// G 招数换人(即使与否在同一行)的数量
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)