我需要使用正则表达式替换许多文件中的某些内容。我是这样做的:
#!/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!"
此代码向用户显示它处理的文件计数。但是我怎么能不计算文件,而是替换呢?处理的每个文件都可以生成零个、一个或多个正则表达式替换。
您可以添加额外的-exec
调用grep
,然后将匹配数传递给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!"
示例(将"之前"替换为"之后"):
$ 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