如何转义文件输出以与'xargs'兼容?

Jac*_*ght 6 unix xargs escape-characters

我有这个命令:

find $1 | xargs touch
Run Code Online (Sandbox Code Playgroud)

但是'名称中包含字符的文件失败并显示“xargs:不匹配的单引号”,我猜其他特殊字符会导致同样的问题。

如何转义输出以便此命令适用于所有文件名?

jll*_*gre 8

这是一种更简单、更快、最便携的方法:

find $1 -exec touch {} +
Run Code Online (Sandbox Code Playgroud)

注意+结束语法。与更流行的\; exec结束语法不同,+打包参数的方式相同xargs

与经常建议的 相比find ... | xargs ...,这find唯一的解决方案更有效,因为:

  • 一个进程正在处理整个任务
  • 不涉及数据管道
  • 不需要与 "\0" hack 相关的额外处理。

与 POSIX 兼容,它也适用于大多数(如果不是所有)当前find实现find -print0xargs -0但它们都是 GNUism。


Maj*_*nko 7

find $1 -print0 | xargs -0 touch
Run Code Online (Sandbox Code Playgroud)

以 \000(字符 0)终止每个文件名,并指示 xargs 期望以 \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.
Run Code Online (Sandbox Code Playgroud)