LoginSignup
39
30

More than 5 years have passed since last update.

`xargs` と `-` の違いについて

Posted at

xargs- の違いについて簡潔にかきたいと思います。

たとえば、

例1
$ find ./*.txt | xargs grep 'hoge'

とか、

例2
$ sed 's/a/c/g' sample_a.txt | diff - sample_b.txt
1c1
< This is c
---
> This is b

など、パイプにからめて使うことがあります。

違いについて

  • xargs は、標準入力を引数のリストとして解釈します。
  • - は、標準入力の内容を、引数(ファイル)の内容として解釈します。

例1は...

findはファイルのリストを返します。
$ bash-3.2$ find ./*.txt
./sample_a.txt
./sample_b.txt

そして、grep は下のように、そのファイルリストをそのまま引数として受取りたいところです。

grep 'hoge' file1.txt file2.txt

ですので、xargs を使います。

例2は...

diff は通常、以下のようにファイル名を引数に持ちます。

diff file1.txt file2.txt

ですが、- によって、標準入力を使うこともできます。

$ diff sample_a.txt -
hoge
1,2c1
< This is a
< hello
---
> hoge

そして、パイプと絡めます。
パイプは、パイプ前部の標準出力を、パイプ後部に標準入力に渡してくれるものです。
ですので、以下のような書き方が有効になります。

sed 's/a/c/g' sample_a.txt | diff - sample_b.txt
39
30
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
39
30