Assuming you want to replace the word 'apple' with 'banana' (exact match) in the contents of the files and not on the names of the files (see my comment above) and that you are using the bash
shell:
#!/bin/bash
COUNTER=0
for file in *.txt ; do
COUNTER=$(grep -o "\<apple\>" $file | wc -l)
sed -i 's/\<apple\>/banana/g' $file
echo "RESULT: $COUNTER replacements in file $file"
let COUNTER=0
done
exit 0;
Explanation:
- To count the replacements for each file you can use
grep
with the -o
flag to print all matches with the word you want replaced (each in a new line) and pipe the result to wc -l
(which counts newlines). The result is stored in a variable which is printed on screen and then reset after each file is processed.
- You must specify the
-i
flag if you want sed
to actually preform the substitution in the files, otherwise the substitution will be performed on the standard output.
- This script will only replace exact matches for the word 'apple'. Thus, the word 'apples', for instance, would not be replaced with 'bananas'. If you want a different behavior just remove the word delimiters around the word 'apple' (word delimiters are
\<
and \>
).