1
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 1 year has passed since last update.

【Linux】findで取得したパスに対してコマンドを実行する方法

Posted at

execオプション

findコマンドのexecオプションを使用することで取得したパスに対してコマンドを実行できます。

以下のように記述すると取得したパス一つ一つに対してコマンドが実行されます。

find . -name "*.txt" -exec rm {} \;

実際に実行されるコマンドは以下のようになります。

$ rm "./sample1.txt"
$ rm "./sample2.txt"
$ rm "./sample3.txt" 
$ rm "./sample4.txt"
$ rm "./sample5.txt"

以下のようにすると取得したパスを並べた状態で引数として実行します。

find . -name "*.txt" -exec rm {} +

実際に実行されるコマンドは以下のようになります。

$ rm "./sample1.txt" "./sample2.txt" "./sample3.txt" "./sample4.txt" "./sample5.txt"

xargsコマンド

またxargsコマンドを使用することで取得したパスに対してコマンドを実行できます。

find . -name "*.txt" | xargs rm

上記のように記述すると以下のようにrmが実行されます。

$ rm "./sample1.txt" "./sample2.txt" "./sample3.txt" "./sample4.txt" "./sample5.txt"

取得したファイルパス一つ一つに対して実行したい場合には以下のようにします。

find . -name "*.txt" | xargs -L 1 rm
$ rm "./sample1.txt"
$ rm "./sample2.txt"
$ rm "./sample3.txt" 
$ rm "./sample4.txt"
$ rm "./sample5.txt"
1
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
1
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?