【问题标题】:Making xargs work in Cygwin使 xargs 在 Cygwin 中工作
【发布时间】:2014-12-19 00:02:29
【问题描述】:

Linux/bash,获取输入行列表并使用xargs 处理每一行:

% ls -1 --color=never | xargs -I{} echo {}
a
b
c

Cygwin,取 1:

$ ls -1 --color=never | xargs -I{} echo {}
    xargs: invalid option -- I
    Usage: xargs [-0prtx] [-e[eof-str]] [-i[replace-str]] [-l[max-lines]]
           [-n max-args] [-s max-chars] [-P max-procs] [--null] [--eof[=eof-str]]
           [--replace[=replace-str]] [--max-lines[=max-lines]] [--interactive]
           [--max-chars=max-chars] [--verbose] [--exit] [--max-procs=max-procs]
           [--max-args=max-args] [--no-run-if-empty] [--version] [--help]
           [command [initial-arguments]]

Cygwin,取 2:

$ ls -1 --color=never | xargs echo
a b c

(是的,我知道ls -1 --color=never | while read X; do echo ${X}; done 有一个通用方法,我已经测试过它在Cygwin 中也可以工作,但我正在寻找一种方法让xargs 在Cygwin 中正常工作)

【问题讨论】:

  • 为我工作。也许你应该更新你的 xargs? xargs (GNU findutils) 4.5.12 由 Cygwin (4.5.12-1) 打包

标签: bash shell cygwin xargs


【解决方案1】:

damienfrancois's 答案是正确的。您可能希望使用-n 强制echo 一次回显一个文件名。

但是,如果您真的对获取每个文件并一次执行一个文件感兴趣,您最好使用find

$ find . -maxdepth 1 --exec echo {} \;

一些事情:

  • 这将选取以句点开头的文件名(包括“.”)
  • 这会将./ 放在您的文件名前面。
  • 所使用的echo 来自/bin/echo,而不是内置的shell 版本的echo。

但是,它不依赖于执行 ls * 的 shell 和导致问题的可能性(例如着色文件名或打印子目录中的文件(您的命令将执行此操作)。

xargs 的目的是尽量减少特定命令的执行:

$ find . -type f | xargs foo

在这种情况下,xargs 将只执行最少的次数foofoo 只会在命令行缓冲区已满或没有更多文件名时执行。但是,如果您在每个名称后强制执行,您最好使用find。它更加灵活,而且您不依赖于 shell 行为。

【讨论】:

  • 发现无法轻松并行化命令,请参阅codereview.stackexchange.com/questions/39377/… 不过,这些都是有价值的提示,谢谢!
  • 应该是find . -maxdepth 1 -exec echo {} \;-exec
  • @mgaert 谢谢。更正了答案。
【解决方案2】:

使用xargs-n 参数,这确实是您应该使用的参数,因为-I 是一个选项,用于给参数一个“名称”,这样您就可以让它们出现在命令行:

$ ls -1 --color=never | xargs echo
a b c
$ ls -1 --color=never | xargs  -n 1 echo
a
b
c

来自手册页:

   -n max-args
          Use at most max-args arguments per command line

   -I replace-str
          Replace occurrences of replace-str in the initial-arguments with names read from standard input.

【讨论】:

  • 他的 Cygwin 版本中没有 -I 选项。这就是为什么他会犯这个错误。但是,您是正确的,他应该使用 -n 来做 OP 想要的事情。 (实际上,他最好用find,但这是另一个答案。
猜你喜欢
  • 1970-01-01
  • 2017-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-04
  • 2015-07-08
  • 1970-01-01
相关资源
最近更新 更多