bash 如何检查 sed 命令是否替换了某个字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15433058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:52:51  来源:igfitidea点击:

How to check if the sed command replaced some string?

linuxbashshellsed

提问by Lukap

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

我如何检查是否发生了更换?(或者发生了多少次?)

采纳答案by Gilles Quenot

sedis not the right tool if you need to count the substitution, awkwill fit better your needs :

如果您需要计算替换,sed不是正确的工具,awk将更适合您的需求:

awk -v OLD=foo -v NEW=bar '
    (
OLD=foo NEW=bar perl -pe '
    $count += s/$ENV{OLD}/$ENV{NEW}/g;
    END{print "$count substitutions occured.\n"}
' "$source_filename"
~ 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 awkand we keep the syntax of sedsubstitution :

这个最新的解决方案只计算被替换的行数。下一个片段使用perl计算所有替换。这个优点比awk我们保留sed替换的语法更清晰:

grep -o 'pattern'|wc -l file && sed 's/pattern/rep/g' oldfile > newfile

Edit

编辑

Thanks to williamwho had found the $count += s///gtrick to count the number of substitutions (even or not on the same line)

感谢威廉找到了$count += s///g计算替换次数的技巧(即使在同一行或不在同一行)

回答by Kent

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.

如果您可以免费选择其他工具,例如 awk,(如@sputnick 建议的那样),请使用其他工具。awk 可以计算模式匹配的次数。

sed itself cannot count replacement, particularly if you use /gflag. however if you want to stick to sedand know the replacement times there is possibilities:

sed 本身不能算替换,特别是如果您使用/g标志。但是,如果您想坚持sed并知道更换时间,则有可能:

One way is

一种方法是

cat file|tee >(grep -o 'pattern'|wc -l)|(sed 's/pattern/replace/g' >newfile) 

you could also do it with tee

你也可以用T 恤做到这一点

kent$  cat file
abababababa
aaaaaa
xaxaxa

kent$  cat file|tee >(grep -o 'a'|wc -l)|(sed 's/a/-/g' >newfile)
15

kent$  cat newfile                                               
-b-b-b-b-b-
------
x-x-x-

see this small example:

看这个小例子:

awk 'END{print t, "substitutions"} {t+=gsub(old,new)}1' old="foo" new="bar" file

回答by Scrutinizer

This awkshould count the total number of substitutions instead of the number of lines where substitutions took place:

awk应该计算替换的总数,而不是发生替换的行数:

awk -v s="OLD" -v c="NEW" '{count+=gsub(s,c); }1
END{print count "numbers"}
' opfilename

回答by Narayan

this worked for me.

这对我有用。

##代码##