Count the number of notes taken with regex

I need to replace something in multiple files with 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 the user the number of files he has been dealing with. But how can I read not files, but replace them? Each processed file can generate zero, one or more replacements with a regular expression.

+4
source share
1 answer

You can add an extra call -execto grep, and then pass the number of matches in awkinstead of the file name:

#!/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
+1
source

Source: https://habr.com/ru/post/1584850/


All Articles