【问题标题】:Escaping an apostrophe with xargs?用 xargs 转义撇号?
【发布时间】:2018-08-26 22:13:18
【问题描述】:

我正在尝试对一堆文件运行命令:

find . -name "*.ext" | xargs -0 cmd

上述方法有效,但它挂起,因为其中一个文件夹愚蠢地在文件名中有一个 ' (其他人有括号和其他废话)。

如何安全地将转义输出发送到我的命令?例如:

cmd foo\ bar\(baz\)\'\!

[编辑] 我知道我可以运行 find ... -exec cmd {} \;,但我正在运行的实际命令更复杂,并且首先通过 sed 进行管道传输

【问题讨论】:

  • @anubhava - 我特别说过我不能那样做 ;)
  • @anubhava - 是的

标签: macos shell xargs


【解决方案1】:

您可以使用此while 循环来处理使用NUL 终止符的find 命令的结果,使用process substitution

while IFS= read -rd '' file; do
   # echo "$file"
   cmd
done < <(find -iname "*.ext" -print0)

这可以处理包含各种空格、全局字符、换行符或任何其他特殊字符的文件名。

请注意,这需要 bash,因为 bourne shell 不支持进程替换。

【讨论】:

    【解决方案2】:

    如果你有 GNU find,你可以使用 -print0 选项

    find -name "*.ext" -print0 | xargs -0 cmd
    

    否则你将不得不放弃xargs。如果你有 Bash,你可以使用

    find -name "*.ext" | while read -a list ; do cmd "${list[@]}" ; done
    

    请注意,您不必将当前目录指定为起点。如果没有指定起始,则假定为.

    【讨论】:

    • -print0 只列出每个文件的一大串(OSX)。第二日我得到read: bad option: -a
    • @MarkKahn -a 是 bash 内置 read 识别的选项。我只能假设您使用的是不同的外壳。
    • @MarkKahn -print0 打印一个 NUL 分隔的文件名列表,xargs -0 期望这样,所以这不是您观察到的一些不正确或意外的行为。
    【解决方案3】:

    GNU Parallel 的诞生正是因为xargs 处理“、”和空格的方式:

    find . -name "*.ext" | parallel cmd
    

    【讨论】:

      猜你喜欢
      • 2013-07-13
      • 2011-09-23
      • 2015-08-27
      • 2016-03-23
      • 2015-05-29
      • 2018-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多