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?

up vote 7 down vote accepted
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
    Useless use of xargs. – user unknown Apr 25 '11 at 23:37

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.

  • Ah, sorry, didn't realise that - you learn something new every day don't you? I retract my comment. – Majenko Apr 26 '11 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 '11 at 20:20

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

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.