
Linuxでは、毎朝1つのフォルダが作成され、そのフォルダに5つのファイルが作成されます。
一日の終わりに(真夜中)、フォルダ内の最後の2つのファイルを削除する必要があります。どうすればいいですか?
答え1
この情報を知らなくても、このコマンドを使用してディレクトリ内の最後の2つのファイルを選択して削除できます。これは、最後の2つのファイルを変更または削除すると仮定します。
$ ls -t | head -n 2 | xargs rm -f
はい
私にこのようなファイルがあるとしましょう。
$ seq 5 | xargs -n 1 touch
$ ls -ltr
total 0
-rw-rw-r--. 1 saml saml 0 Jun 5 04:01 1
-rw-rw-r--. 1 saml saml 0 Jun 5 04:01 2
-rw-rw-r--. 1 saml saml 0 Jun 5 04:01 3
-rw-rw-r--. 1 saml saml 0 Jun 5 04:01 4
-rw-rw-r--. 1 saml saml 0 Jun 5 04:01 5
を使用すると、ls -t | head -n 2
最後に変更された2つのファイルが提供されます。
$ ls -t | head -n 2
5
4
転送してxargs rm -f
削除できます。
$ ls -t | head -n 2 | xargs rm -f
$ ls -tr
total 0
-rw-rw-r--. 1 saml saml 0 Jun 5 04:01 1
-rw-rw-r--. 1 saml saml 0 Jun 5 04:01 2
-rw-rw-r--. 1 saml saml 0 Jun 5 04:01 3
答え2
zshの使用
rm -f -- *(D.om[1,2])
現在のディレクトリから最新の(最後の修正基準)2つの一般ファイルを削除します。
GNUツールの使用:
eval "files=($(ls -At --quoting-style=shell-always))"
n=2
for f in "${files[@]}"; do
if [[ -f $f && ! -L $f ]]; then
rm -f -- "$f"
((--n)) || break
fi
done