Monday, February 25, 2013

Solaris find and xargs with files and directories containing spaces

Solaris does not ship with gnu standard tools like 'find' and 'xargs'. These two GNU commands play nicely together even when there are directory and file names with spaces (find -print0, xargs -0).

That is not the case for Solaris and other Unix systems. You need to get a little more creative there. Basically you will need to use an intermediate command to quote the resulting lines from find so xargs can parse them correctly.

As an example in Solaris you would find an occurrence of a pattern string inside all files starting at a given directory (in case blanks are expected in names) as shown below:
$ find /path/to/dir/ -name "*" | sed 's/.*/"&"/' | xargs grep "searchedPattern"

4 comments:

Florian Feldhaus said...

Thanks for this helpful hint! The only problem I'm left with now are newlines in filenames. Do you know any way to make find output newlines with a \n instead of the newline?

Nestor Urquiza said...

@Florian perhas with a test case I can help you better. Please share simple commands illustrating your issue and I will try to help. Best,

Florian Feldhaus said...

Sure. I'm currently checking large filesystems and some users have created files with newlines in the filename. Here's an example

touch "test
"
touch test2
find . -type f

Now you will notice, that find outputs the filename including the newline. Thus piping the filename to another tool like sed does not work. Do you have an idea how to handle this?

Nestor Urquiza said...

I see now. The old newline in filename discussion. This is huge (read http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html) but to simplify I suggest you consider filenames with newlines invalid. Any code generating them should be fix. If that is not possible (like when you do not own the code generating them, you will need to rename them as I just posted in http://thinkinginsoftware.blogspot.com/2013/09/reconsider-those-newline-in-filename.html

Followers