0
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コマンド】特定のファイルを絞り込んでそれ以外を削除する

Last updated at Posted at 2022-04-26

ディレクトリ内のファイルを絞り込んでそれ以外を削除したい

linux % ls -la
total 0
drwxr-xr-x   9 user  group   288  4 26 22:51 .
drwxr-xr-x+ 63 user  group  2016  4 26 23:05 ..
drwxr-xr-x   2 user  group    64  4 26 22:44 dir1
drwxr-xr-x   2 user  group    64  4 26 22:44 dir2
drwxr-xr-x   2 user  group    64  4 26 22:44 dir3
-rw-r--r--   1 user  group     0  4 26 22:44 file1.txt
-rw-r--r--   1 user  group     0  4 26 22:44 file2.txt
-rw-r--r--   1 user  group     0  4 26 22:44 file3.txt
-rw-r--r--   1 user  group     0  4 26 22:45 file4.txt

手順

grepで''内のファイルを絞り込み
echoで絞り込まれている内容を確認

ls | grep -i -v -E '残したいディレクトリ名|ファイル名' | xargs -n 1 echo
-n 1とすることで標準入力から受け取るパラメータを1つずつに

linux % ls | grep -i -v -E 'dir1|dir2|file2.txt' | xargs -n 1 echo
dir1
dir2
file2.txt

絞り込んだ以外のファイル以外をechoからrm -frに書き換えて削除
ls | grep -i -v -E 'dir1|dir2|file2.txt' | xargs rm -rf

linux % ls -la
total 0
drwxr-xr-x   5 user  group   160  4 26 23:21 .
drwxr-xr-x+ 63 user  group  2016  4 26 23:21 ..
drwxr-xr-x   2 user  group    64  4 26 22:44 dir1
drwxr-xr-x   2 user  group    64  4 26 22:44 dir2
-rw-r--r--   1 user  group     0  4 26 22:44 file2.txt

参考

メモ書き

0
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
0
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?