Showing posts with label xargs. Show all posts
Showing posts with label xargs. Show all posts

Sunday, January 13, 2013

Piping "find" results through xargs

Piping the results of find using xargs doesn't typically work exactly how I want. If a file or folder has a space in its name xargs doesn't handle it correctly.
From the xargs man page:
Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you.
So, long story short: add "-print0" to find, and "-0" to xargs:

find . -name "*txt" -print0 | xargs -0 grep -i poisson

Friday, January 27, 2012

Using -exec instead of xargs

Using xargs to pipe results of find into grep has problems if find returns files/folders with spaces in the name.

find ./ -name "*html" | xargs grep "something"


Ends up giving me lots of "file doesn't exist" errors.

Using exec circumvents this problem, although using exec is apparently a less efficient way of doing things.

find ./ -name "*html" -exec grep -H "something" "{}" \;

-H tells grep to always show the filename, otherwise you only get the match.
"{}" represents the filename returned by find.
\; I'm not sure what this is, but it has to be there...

Update:
I describe a slightly simpler solution in this posting.