Help us understand the problem. What is going on with this article?

findで空白の入っているファイルに対して処理する3つの方法

More than 3 years have passed since last update.
├── answer.txt
├── test 01.txt
├── test 02.txt
└── test 03.txt

上記のようなディレクトリで、test*.txtを削除したい場合。

-execを使う

$ find ./ -type f -name "test*" -exec rm {} \;

-execで各行に対してコマンドを発行できる。
find結果は{}に入る。

-execが使えるのはfind結果そのものに対してのみ。
find結果に対してgrepかけてからrmしたいとか、そういう場合はxargsを使う必要がある。

xargsを使う場合

普通にfindとxargs rmとかやるとエラーが出る。パスに空白が入っているからね。

$ find ./ -type f -name "test*" | xargs rm
rm: .//test: No such file or directory
rm: 01.txt: No such file or directory
rm: .//test: No such file or directory
rm: 02.txt: No such file or directory
rm: .//test: No such file or directory
rm: 03.txt: No such file or directory

そんな時は区切り文字を`\0'にしてしまおう。

$ find ./ -type f -name "test*"  -print0 | xargs -0 rm

xargsを拡張する

各行をダブルクォートで囲ってしまおう。

alias xxargs='perl -nle '\''print "\"$_\""'\'' | xargs'

これ定義してからこんな風に使う。

$ find ./ -type f -name "test*" | xxargs rm
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away