Celeb Glow
news | March 25, 2026

How do I grep a exact string from multiple files at the same time? [closed]

I have multiple files(text file) in a folder like below where the 1st file contains some paths as a string and the other with path+file_name.

File1:

# pwd
/root/test
# cat file1.txt
/abc/bce/12345/input/part3
/abc/bce/12345/input/part3/err
/abc/bce/34563/input
/abc/bce/34563/input/part1
/abc/bce/34563/input/part3/wrk
/abc/bce/11198/input/VII
/abc/bce/11198/input/VII/err
/abc/bce/11198/input/VII/part3
/abc/bce/11198/input/VII/part3/err
#

File2:

# pwd
/root/test/test
# cat file2.txt
/abc/bce/12345/input/part3/AIR9905.txt--20210421--
/abc/bce/12345/input/part3/AIR9923.txt--20210315--
/abc/bce/12345/input/part3/err/AIR9950.txt--20200512--
#

File3:

# pwd
/root/test/test
# cat file3.txt
/abc/bce/12345/input/part3/err/AIR1034.txt--20210110--
/abc/bce/34563/input/part1/AIR3426.txt--20200420--
/abc/bce/11198/input/VII/part3/err/V.AIR7650.txt--20170625--
#

Present output:

test/file2.txt:/abc/bce/12345/input/part3/AIR9905.txt--20210421--
test/file2.txt:/abc/bce/12345/input/part3/AIR9923.txt--20210315--
test/file2.txt:/abc/bce/12345/input/part3/err/AIR9950.txt--20200512--
test/file3.txt:/abc/bce/12345/input/part3/err/AIR1034.txt--20210110--

Expected Output:

test/file2.txt:/abc/bce/12345/input/part3/AIR9905.txt--20210421--
test/file2.txt:/abc/bce/12345/input/part3/AIR9923.txt--20210315--

I am using grep -rHw "/abc/bce/12345/input/part3" test/ to match the line from file1 and extract their info from file2,file3,.... so on. However the problem lies, when I take the 1st line from file1 and try to retrieve the path+File_name, it takes all the similar lines from file2,file3, and so on. But I want to get lines in file2.txt, file3.txt, ... that (a) contain the string "/abc/bce/12345/input/part3" + an added string (the filenames), but (b) don't contain the other "/abc/bce/12345/input/part3/err" string.

 I don't know how I can do that when file1 is being compared with multiple files in a continuous manner. I need a generalized solution for all cases. Please let me know if there are any other ways to get this done through the shell script. 
2

2 Answers

It's called negative lookahead (?!)

grep -Pr '/abc/bce/12345/input/part3/(?!err)' test/

If you want to use file1.txt as a list of patterns:

grep -e err$ test/file1.txt | grep --include='file[2-3].txt' -vrFf - test/test
1
find . -type f -name 'file[2-3].txt' -exec grep -P '/abc/bce/12345/input/part3/(?!err)' {} \;
2