4

I need to replace something in a number of files using regex. I do it like this:

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

This code shows user the count of files it dealed with. But how could I count not files, but replaces? Every file handled could produce zero, one or many replaces with regex.

1

1 Answer 1

1

You can add an extra -exec call to grep, then pass the number of matches to awk instead of just the filename:

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

Example (replacing "before" with "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

Not the answer you're looking for? Browse other questions tagged or ask your own question.