3

How to find files with a specific pattern in the parent and child directory of my present working directory using a single command ?

Filename - test.txt, the file has the pattern nslookup

This file is present in 3 directories and they are /home, /home/1 and /home/1/2

I am currently at /home/1. I have tried below commands :

find ../ -type f -name "test.txt"

Output :

../test.txt
../home/1/test.txt
../home/1/2/test.txt

I was able to find the files, hence I tried the below command :

$ find ../ -type f -exec grep "nslookup" {} \;
nslookup
nslookup
nslookup

This doesn't display the file names.

Command :

find . -type f -name "test.txt" | xargs grep "nslookup"

==> gives me files in pwd and child directories :

./1/test.txt:nslookup
./test.txt:nslookup

but when I try to search in the parent directory as shown below the results are erroneous :

find ../ -type f -name "test.txt" | xargs grep "nslookup"

User@User-PC ~/test
$ uname -a
CYGWIN_NT-6.1 User-PC 2.5.2(0.297/5/3) 2016-06-23 14:29 x86_64 Cygwin
3
  • Have you tried grep -irn?
    – vol7ron
    Commented Jul 22, 2018 at 18:51
  • @vol7ron - my kids love your username 8-). Good taste in using the original image for your profile.
    – slm
    Commented Jul 22, 2018 at 23:22
  • That’s sweet! :D <3
    – vol7ron
    Commented Jul 22, 2018 at 23:35

1 Answer 1

4

Your command

find ../ -type f -exec grep "nslookup" {} \;

is almost correct, apart from the fact that grep by default does not display the filename when it is given only a single file to work with.

Here are two ways of fixing this:

  1. Using a grep that has the non-standard (but common) -H option to always display the filename:

    find ../ -type f -exec grep -H 'nslookup' {} \;
    
  2. Giving grep at least two filenames:

    find ../ -type f -exec grep 'nslookup' /dev/null {} \;
    

If you are interested in only the filenames, then these are two ways of doing this:

  1. Use the standard -l option with grep:

    find ../ -type f -exec grep -l 'nslookup' {} \;
    
  2. Let find output the pathname of the file if it contains a match:

    find ../ -type f -exec grep -q 'nslookup' {} \; -print
    

    Here, we only use grep to detect if the pattern matches. Its -q option stops it from outputting anything and find will use the exit status of the utility to determine whether to do the -print action or not.

1
  • 2
    Have you thought about penning a unix text ? IMO, Stephane & you can team up and that would bring breadth, depth, and clarity into the picture which will be hard to match. Commented Jul 22, 2018 at 20:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .