【问题标题】:How to copy files found with grep on OSX如何在 OSX 上复制使用 grep 找到的文件
【发布时间】:2019-04-15 13:20:11
【问题描述】:

我想复制我在 OSX 系统上使用grep 找到的文件,其中cp 命令没有-t 选项。

A previous posts' solution 做这样的事情依赖于cp 中的-t 标志。但是,就像那张海报一样,我想获取从grep 收到的文件列表,然后对其执行命令,例如:

grep -lr "foo" --include=*.txt * 2>/dev/null | xargs cp -t /path/to/targetdir

【问题讨论】:

    标签: macos grep pipe xargs cp


    【解决方案1】:

    效率低于cp -t,但这可行:

    grep -lr "foo" --include=*.txt * 2>/dev/null |
      xargs -I{} cp "{}" /path/to/targetdir
    

    解释:

    对于filenames | xargs cp -t destinationxargs 将传入的文件名更改为这种格式:

    cp -t destination filename1 ... filenameN
    

    也就是说,它只运行cp 一次(实际上,每几千个文件名运行一次——xargs 如果对 shell 来说太长,会破坏命令行)。

    另一方面,对于filenames | xargs -I{} cp "{}" destinationxargs 将传入的文件名更改为这种格式:

    cp "filename1" destination
    ...
    cp "filenameN" destination
    

    即,它为每个传入的文件名运行一次cp,这要慢得多。对于大量(例如,>10k)非常小的(例如,

    PS:另一种流行的技术是使用findexec 函数而不是xargs,例如https://stackoverflow.com/a/5241677/1563960

    【讨论】:

      猜你喜欢
      • 2016-09-20
      • 1970-01-01
      • 2020-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      相关资源
      最近更新 更多