1

I am trying to search for the string "rGEO" in a directory by using the following commands:

find . -name "*" -type f -print | xargs grep "rGEO" 
./home/oper1/AgencyTape/geo/exe/gngeo.cmd:${WEB_DIR}/exe/web_reports.sh -aGN -d${prev_ccyy}${prev_mm} -rGEO -nomail

In this case, I get back the file name which has the matching line, as well as the line which matches the above string.

find . -name "*" -type f -exec grep "rGEO" {} \;

In this case, I get back:

${WEB_DIR}/exe/web_reports.sh -aGN -d${prev_ccyy}${prev_mm} -rGEO -nomail

The file which contains the line isn't printed - and, as you can see, there is a lot of difference between the two outputs.

Using xargs gives more clear and precise output.

My question is: what is the difference between the two commands? To me, they seem to be performing the same logic, but getting different results.

Mat
  • 202,337
  • 40
  • 393
  • 406
Subhayan Bhattacharya
  • 5,407
  • 7
  • 42
  • 60
  • Not quite a duplicate of [Which is faster, 'find -exec' or 'find | xargs -0'?](https://stackoverflow.com/questions/980411/which-is-faster-find-exec-or-find-xargs-0) since this asks about the differences and that question asks about which is faster, but the difference is that `xargs` invokes the command in batches while `find -exec` invokes the command once per result, which makes `xargs` faster. – Adam Katz Feb 13 '16 at 00:42
  • More to the point: `find -exec` is pretty much identical to `find -print0 |xargs -0n1` since `-n1` ensures one call per result. – Adam Katz Feb 13 '16 at 00:44

2 Answers2

6

what is the difference between the two commands? To me, they seem to be performing the same logic, but getting different results.

Below is one major difference between xargs and exec:

find . -name "*.c" -exec ls -al {} \; executes the command ls -al on each individual file.

find . -name "*.c" | xargs ls -al constructs an argument list from the output of the find command and passes it to ls.

consider the below produced output of the find command:

a.c
b.c
c.c

the first command(exec) would execute

ls -l a.c
ls -l b.c
ls -l c.c

but the second (xargs) would execute

ls -l a.c b.c c.c

Hope this helps.

neo
  • 969
  • 1
  • 11
  • 23
0

Adding -print will return the name of the file also, although in all little different way.

find . -name "*" -type f -exec grep "rGEO" {} \; -print

I am not aware of the internal working, here is how it differs. Suppose find commands finds 2 files a.txt and b.txt

-exec will work on them like.

grep "rGEO" a.txt
grep "rGEO" b.txt

however xargs will work like..

grep "rGEO" a.txt b.txt.

Hope it helps

ghitesh
  • 160
  • 2
  • 14