不明な番号を含むファイルを削除する方法は?

不明な番号を含むファイルを削除する方法は?

次の名前のファイルを作成するコードがあります。

body00123.txt
body00124.txt
body00125.txt

body-1-2126.txt
body-1-2127.txt
body-1-2128.txt

body-3-3129.txt
body-3-3130.txt
body-3-3131.txt

これにより、ファイルの最初の2つの数字は「負の数」になりますが、最後の3つの数字はそうではありません。

次のリストがあります。

123
127
129

これらの数字の1つで終わらないすべてのファイルを削除したいと思います。必要な残りのファイルの例は次のとおりです。

body00123.txt

body-1-2127.txt

body-3-3129.txt

私のコードはPythonで実行されているので、次のことを試しました。

for i not in myList:
     os.system('rm body*' + str(i) + '.txt')

これにより、すべてのファイルが削除されます。

ベストアンサー1

時には、「良い」ファイルを別の場所に移動し、悪いファイルを削除してから、良いファイルを再度移動する方が簡単です。

方法が適切であれば、これがうまくいく可能性があります。

#!/bin/sh

# Temporary directory to hold the files we want to keep
mkdir .keep || exit

for a in $(cat keeplist)
do
  # These are the files we want to keep
  mv body*$a.txt .keep

  # Except this might match negative versions, so remove them
  rm -f .keep/*-$a.txt
done

# Remove the files we don't want
rm body*

# Move the good files back
mv .keep/* .

# Tidy up
rmdir .keep

たとえば、次のように起動した場合:

% ls
body-1-2126.txt  body-2-3-123.txt  body-3-3131.txt  body00125.txt  s
body-1-2127.txt  body-3-3129.txt   body00123.txt    fix
body-1-2128.txt  body-3-3130.txt   body00124.txt    keeplist

その後、私たちが終わるスクリプトを実行します

% ls
body-1-2127.txt  body-3-3129.txt  body00123.txt  fix  keeplist  s

おすすめ記事