如何检查是否sed命令替换一些字符串? [英] How to check if the sed command replaced some string?

查看:218
本文介绍了如何检查是否sed命令替换一些字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该命令替换旧的字符串,如果存在一个新的。

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)

这篇关于如何检查是否sed命令替换一些字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆