0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Macのターミナルで複数ディレクトリの中の一つのファイルだけコピーしたかった物語

Last updated at Posted at 2018-11-30

動機

複数ディレクトリの中にある複数ファイルからファイルをひとつだけ取り出して別ディレクトリにコピーしたいと思いました。Macで。なるべく無駄なく。

結論

ディレクトリ構造がdirectory/subdirectories/files.txtだった場合。

echo directory/* | xargs -n 1 sh -c 'find $0 | sort | head -n 2 | grep .txt | xargs -I{} cp {} toDirectory/'

キモ

まず、echo directory/*でサブディレクトリだけ表示させます。
それをxargs -n 1でひとつづつ次のコマンドに渡します。
で、サブディレクトリの中身をfindして、今回はアルファベット順で先頭になるファイルだけ用いたかったので、sortをかけます。そして、head -n 2で先頭2行だけを取得。1行目はサブディレクトリ名、2行目はアルファベット順で先頭になるファイルです。今回ファイル名には.txtの拡張子がついているので、grep .txtでそれを抜き出します。ここはhead -n 2 | tail -n 1でもいいです。
それをさらにxargsに渡して、こんな感じに変数を作ってcpに渡します。
ここ、普通にGNU cpならxargs cp --target-directory=toDirectoryでいいのですが、Macのcpは実は--target-directoryおよび-tオプションがないらしいのです。なので、こんな書き方をするそうです。

参考ページ

http://web.sfc.wide.ad.jp/~sagawa/gnujdoc/coreutils-5.0/coreutils-ja_2.html#SEC6
https://lukesilvia.hatenablog.com/entry/20081026/p1

募集

もっとこんな風に書けるよ、というものがあったらぜひ教えてください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?