Ten files located in a directory. Each file content has "apple" word. write a bash shell script to replace "apple" with "banana" in all ten files and Print the number of replacements for each file. Have tried in this way but dont know how to get number of replacement. can anyone help in this ? and sed is only modifying in display actual file not getting modified
for f in *.txt
do sed 's/apple/banana/g' $f
Best How To :
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
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"
- 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