Reputation: 291
I have folder that contains about a 100 files. I want to search for a specific word in each file, pick up only those lines from each file and put them in separate files. For example:
Look for lines that contain the word "HELLO" (case-sensitive) in FILE1.txt, FILE2.txt, FILE3.txt.
From FILE1, copy those lines and put them in a new file, FILE1_BK.txt
From FILE2, copy those lines and put them in a new file, FILE2_BK.txt
From FILE3, copy those lines and put them in a new file, FILE3_BK.txt
I know how to do this one file at a time but am unable to write the script for multiple files at once.
grep "HELLO" FILE1.txt > FILE1_BK.txt
Need to incorporate it in the loop.
for f in myFolder; do something; done;
Thanks in advance!
Upvotes: 0
Views: 1895
Reputation: 2496
Lets say you have filepaths stored in a file named filenames.txt Then you can do:
while read -r filepath; do
grep -r "pattern" $filepath > "$filepath""-output"
done < filenames.txt
This obviously assumes all filepaths are in new lines in filenames.txt
Upvotes: 1
Reputation: 12356
Why loop through it manually? Why not grep "HELLO" *.txt > FILE1_BK.txt
?
for f in *.txt; do
grep "HELLO" $f > $f_found.txt;
done
Upvotes: 1