计算使用正则表达式替换的次数

时间:2015-04-27 08:33:27

标签: regex bash

我需要使用正则表达式替换多个文件中的内容。我是这样做的:

#!/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!"

此代码向用户显示其处理的文件数。但我怎么能算不是文件,而是替换?处理的每个文件都可以产生零,一个或多个替换正则表达式。

1 个答案:

答案 0 :(得分:1)

您可以向-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