"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 ..

"cp"コマンドを使用して、現在のディレクトリにファイルのコピーをテストします。

 find ~ -type f -iregex '.*linux.*\.pdf' -print0 | xargs -0 cp .

エラー発生:

    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

コマンドの置き換えで問題を解決しました。

    cp $(find ~ -type f -iregex '.*linux.*\.pdf' -print0) .

それを実装する方法xargs

ベストアンサー1

cpエラーが示すように、ターゲットディレクトリは最後のディレクトリである必要があります。そのオプションにcp対応するGNUがないようであるため、xargsを使用してファイル名と間にファイル名を挿入する必要があります。cp-tcp.

find ... | xargs -0 -I _ cp _ .

whereは、-I入力に置き換えられる文字列を知らせるために使用されます(この場合はitを使用します_が、{}一般的に使用されます)。

もちろん、これは自分で行うことができますfind

find ~ -type f -iregex '.*linux.*\.pdf' -exec cp {} . \;

おすすめ記事