7
3

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.

xargsコマンド

Posted at

xargsはあるコマンドを引数として追加のコマンドを実行できる。

[command1] で実行して得た引数を元に [command2] を実行する

$ [command1] | xargs [command2]

xargsを用いると複数条件検索ができるのでfindgrepとの併用が便利。

# 現階層におけるrtf形式のファイルで内容に2が含まれるもの
$ find . -name "*.rtf" | xargs grep 2

でもこれだと条件によっては一気に出てしまうので、不便。。

だから各ファイルづつ出力を待ってもらうようにする

# optionで -p を指定して確認を挟む
$ find . -name "*.rtf" | xargs -p  grep 2

# これらのファイル検索するよと聞かれるので 'y' or 'Y' で回答
grep 2 ./huga.rtf ./hugahuga.rtf ./hogehoge.rtf ./hogera.rtf ./piyo.rtf?...y

# 応答
./hugahuga.rtf:32131
./hugahuga.rtf:bzber2
./hugahuga.rtf:4251
./hogehoge.rtf:222
./hogehoge.rtf:62
./hogehoge.rtf:462
./hogera.rtf:222

これだと結果変わらないので、-Lで試行ファイル数を意図的に変更できる。

-Lの後ろに数字を指定し、そのファイル数ごとに出力をストップさせる

# 1ファイルごとに出力ストップ
$ find . -name "*.rtf" | xargs -L1 -p grep 2
grep 2 ./huga.rtf?...y
grep 2 ./hugahuga.rtf?...y
32131
bzber2
4251
grep 2 ./hogehoge.rtf?...y
222
62
462
grep 2 ./hogera.rtf?...y
222
grep 2 ./piyo.rtf?...y
# 2ファイルごとに出力ストップ
$ find . -name "*.rtf" | xargs -L2 -p grep 2
grep 2 ./huga.rtf ./hugahuga.rtf?...y
./hugahuga.rtf:32131
./hugahuga.rtf:bzber2
./hugahuga.rtf:4251
grep 2 ./hogehoge.rtf ./hogera.rtf?...y
./hogehoge.rtf:222
./hogehoge.rtf:62
./hogehoge.rtf:462
./hogera.rtf:222
grep 2 ./piyo.rtf?...y

ヒットするものだけが返ってきたらベストだけど、そこまではよく分からない、、(泣

7
3
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
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?