计算使用正则表达式替换的次数
发布时间:2020-12-14 05:47:19 所属栏目:百科 来源:网络整理
导读:我需要使用正则表达式替换许多文件中的内容.我是这样做的: #!/usr/bin/env bashfind /path/to/dir -type f -name '*.txt' -exec perl -e 's/replaceWhat/replaceWith/ig' -pi '{}' ; -print | awk '{count = count+1 }; END { print count " fil
我需要使用正则表达式替换许多文件中的内容.我是这样做的:
#!/usr/bin/env bash find /path/to/dir -type f -name '*.txt' -exec perl -e 's/replaceWhat/replaceWith/ig' -pi '{}' ; -print | awk '{count = count+1 }; END { print count " file(s) handled" }' echo "Done!" 此代码向用户显示其处理的文件数.但我怎么能算不是文件,而是替换?处理的每个文件都可以使用正则表达式进行零次,一次或多次替换. 解决方法
您可以向grep添加额外的-exec调用,然后将匹配数传递给awk而不仅仅是文件名:
#!/usr/bin/env bash find /path/to/dir -type f -name '*.txt' -exec grep -c 'replaceWhat' '{}' ; -exec perl -e 's/replaceWhat/replaceWith/ig' -pi '{}' ; | awk '{count += $0 }; END { print count " replacement(s) made" }' echo "Done!" 示例(将“before”替换为“after”): $tail -n +1 *.txt ==> 1.txt <== before foo bar ==> 2.txt <== foo bar baz ==> 3.txt <== before foo before bar before $./count_replacements.sh 4 replacement(s) handled $tail -n +1 *.txt ==> 1.txt <== after foo bar ==> 2.txt <== foo bar baz ==> 3.txt <== after foo after bar after (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |