user180946 user180946 - 4 months ago 8
Bash Question

search a string in a file which is also present in another file in unix

I am new to Unix and had below requirement to finish my task.

I have

file1.dat
which has data as shown below.

case1.txt
case2.txt
case3.txt
case4.txt
case5.txt


file1.dat has only file names

I have folder which has above files mentioned in file1.dat

./all_files
case1.txt
case2.txt
case3.txt
case4.txt


data in case1.txt, case2.txt, case3.txt:

step1
step2
step3
step4


Now, I have to take particular step say step2 from each file, which is also present in file1.dat

Note: step2 is not line no:2 always.

Answer
while read f; do
    test -f "$f" && grep -F 'step2' "$f"
done <file1.dat

The lines of file1.dat (containing filenames) are read one by one into the f variable.

The body of the while-loop tests to make sure the file $f exists before using grep to look for the text string step2 in the given file.

A slightly more verbose (but equivalent) version of the loop:

while read f; do
    if [ -f "$f" ]; then
        grep -F 'step2' "$f"
    fi
done <file1.dat

Depending on where you run this, you might have to modify the grep command slightly. For example, if you run this in the folder just above the subfolder with all the files:

grep -F 'step2' "all_files/$f"

It wasn't entirely clear in the question, but easily adjustable if needs be.

Of course, you could just bypass the file1.dat altogether and say

grep -F 'step2' all_files/case?.txt

without looping at all.

Edit: with new requirements:

find ./all_files -type f -name "case?.txt" -print0 |
xargs -0 grep -l -F 'step2'

This will recursively search through all folders under the all_files folder, find the files matching case?.txt, and report which ones contains the wanted string.

You may want to change the pattern to be more strict, maybe to something like case[1-5].txt.