我需要使用regex替换一些文件中的内容。我是这样做的:
#!/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!"此代码向用户显示它所处理的文件数。但是我怎么能不计算文件,而是替换文件呢?处理的每个文件都可能产生零个、一个或多个regex替换。
发布于 2015-04-27 17:15:44
您可以向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!"示例(替换“之前”为“之后”):
$ 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
afterhttps://stackoverflow.com/questions/29890824
复制相似问题