LoginSignup
7

More than 5 years have passed since last update.

Bashを使ってカレントディレクトリでファイルのみ操作する

Last updated at Posted at 2015-01-16

カレントディレクトリにディレクトリとファイルが混在している時に、ファイルのみ、コピーや削除をしたいことが時々あります。そのような時、今は以下のコマンドを使っています。

$ ls -F|grep -v /|xargs -i cp {} ./path/to/dest # ファイルのみコピー
$ ls -F|grep -v /|xargs rm                      # ファイルのみ削除

ただし、カレントディレクトリに実行可能なファイルやシンボリックリンクが含まれているとうまく動きません。

# 実行可能なファイルの例
$ ls -F
dir/ exec.sh* file.txt
$ ls -F|grep -v /|xargs rm
rm: cannot remove `exec.sh*': No such file or directory
$ ls -F
dir/ exec.sh*

これは、 ls -F が、実行可能なファイルの末尾に * を、シンボリックリンクの末尾に @ を追加したリストを返すからです(他にもFIFOには | が、ソケットには = が追加されるらしい)。

そこで、こうした場合は sed で応急処置をしています。

ls -F|grep -v /|sed -e "s/\*//g" |xargs rm

さすがに長さを感じて、 find を試してみたりもしましたが

find . -maxdepth 1 -type f |xargs rm

maxdepth が長くて、結局打ち慣れた ls に戻っています。

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