ksaitoの日記

日々試したことの覚え書き

findの結果をxargsで処理する

移転しました。

自動的にリダイレクトします。

findの結果は、xargsで処理すると早くて便利です。
findのexecオプションより早く適切に処理してくれます。

$ find test -type f 
test/b.txt
test/a.txt
test/c.txt
$ find test -type f | xargs file
test/b.txt: empty
test/a.txt: empty
test/c.txt: empty
$ 

ファイル名やディレクトリ名にスペースが含まれていると正しく処理してくれません。

$ find directory\ name/ -type f
directory name/dummy.bin
directory name/dummy.txt
$ find directory\ name/ -type f -print | xargs ls
ls: directory にアクセスできません: そのようなファイルやディレクトリはありません
ls: name/dummy.bin にアクセスできません: そのようなファイルやディレクトリはありません
ls: directory にアクセスできません: そのようなファイルやディレクトリはありません
ls: name/dummy.txt にアクセスできません: そのようなファイルやディレクトリはありません
$ 

こんな時は、findのprint0オプションでデータをnull区切りで出力し、xargsの0オプションでnull区切りのデータとして処理します。

$ find directory\ name/ -type f -print0 | xargs -0 ls
directory name/dummy.bin  directory name/dummy.txt
$

例えば、Subversionからチェックアウト済みのスペース混じりのファイルの中でtxtファイル以外が全部バイナリだったとします。
txtファイル以外のバイナリファイルだけにsvn:needs-lock属性を追加するときには次のようにします。

$ find . -type d -name '.svn' -prune -o -type f -a \( ! -name *.txt \) -print0 | xargs -0 svn propset svn:needs-lock '*'