如何检查是否sed命令替换一些字符串?

编程入门 行业动态 更新时间:2024-10-12 16:28:32
本文介绍了如何检查是否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命令替换一些字符串?

本文发布于:2023-11-30 07:06:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649115.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   命令   sed

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!