7

I have this command:

find $1 | xargs touch

But files with ' characters in their names fail with "xargs: unmatched single quote", and I guess other special characters would cause the same problem.

How can I escape the output so this command works with all filenames?

3 Answers 3

7
find $1 -print0 | xargs -0 touch

That terminates each filename with \000 (character 0) and instructs xargs to expect the filenames terminated by \000

   -print0
          True; print the full file name on the standard output,  followed
          by  a  null  character  (instead  of  the newline character that
          -print uses).  This allows file names that contain  newlines  or
          other  types  of white space to be correctly interpreted by pro‐
          grams that process the find output.  This option corresponds  to
          the -0 option of xargs.
1
  • 1
    Useless use of xargs. Apr 25, 2011 at 23:37
8

Here is the simpler, faster and most portable way to do it :

find $1 -exec touch {} +

Note the + ending syntax. Unlike the more popular \; exec ending syntax, + is packing arguments the same way xargs does.

Compared to the often suggested find ... | xargs ..., this find only solution is more efficient because:

  • a single process is handling whole task
  • no data piping is involved
  • no extra processing associated with the "\0" hack is required.

Being POSIX compliant, it also works with most if not all current find implementations unlike find -print0 and xargs -0 which are both GNUisms.

2
  • Ah, sorry, didn't realise that - you learn something new every day don't you? I retract my comment.
    – Majenko
    Apr 26, 2011 at 9:31
  • Every single day indeed ! Moving then most of my now retracted answer to your retracted comment to my unretracted reply ;)
    – jlliagre
    Apr 26, 2011 at 20:20
1

If your input is not from find, but from some other line-generating program, you may want to have a look at GNU Parallel which deals nicely with filenames containing ' " and space:

find | parallel touch

Watch the intro video to learn more: Part 1: GNU Parallel script processing and execution

You must log in to answer this question.

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