最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

SEO心得admin89浏览0评论
本文介绍了如何检查是否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)

发布评论

评论列表(0)

  1. 暂无评论