使用命令 `xargs` 复制多个文件

Abs*_*cDo 11 bash xargs

我想将命令搜索到的文件复制find到当前目录

    # find linux books
    find ~ -type f -iregex '.*linux.*\.pdf' -print0 | xargs -0 echo
  # the result
    ../Books/LinuxCollection/Linux_TLCL-17.10.pdf ../Richard Blum, Christine Bresnahan - Linux Command Line and Shell Scripting Bible, 3rd Edition - 2015.pdf ..
Run Code Online (Sandbox Code Playgroud)

测试使用命令 `cp' 将文件复制到当前目录

 find ~ -type f -iregex '.*linux.*\.pdf' -print0 | xargs -0 cp .
Run Code Online (Sandbox Code Playgroud)

获取错误:

    usage: cp [-R [-H | -L | -P]] [-fi | -n] [-apvXc] source_file target_file
           cp [-R [-H | -L | -P]] [-fi | -n] [-apvXc] source_file ... target_directory
Run Code Online (Sandbox Code Playgroud)

我解决了命令替换的问题

    cp $(find ~ -type f -iregex '.*linux.*\.pdf' -print0) .
Run Code Online (Sandbox Code Playgroud)

如何完成它xargs

mur*_*uru 17

cp错误所示,目标目录必须放在最后。因为它看起来像你cp没有GNU的等效cp-t选项,你必须得到xargs的插入的文件名cp.

find ... | xargs -0 -I _ cp _ .
Run Code Online (Sandbox Code Playgroud)

where-I用于告诉哪个字符串将被输入替换(在这种情况下,我使用的是_,但{}也常用)。

当然,这可以通过find自己来完成:

find ~ -type f -iregex '.*linux.*\.pdf' -exec cp {} . \;
Run Code Online (Sandbox Code Playgroud)

  • 提示:如果您的命令还包含下划线,请不要使用 -I _。我花了太长时间才弄明白这一点。 (4认同)