フォルダ内の最新のファイルを除くすべてのファイルを削除する方法は? [コピー]

フォルダ内の最新のファイルを除くすべてのファイルを削除する方法は? [コピー]

CentOS 7を使用しています。特定のディレクトリから最新のファイルを除くすべての「* .log」ファイルを削除したいと思います。私はこれを試しました

[rails@server ~]$ ls -t ~/.forever | tail -n +2 | xargs rm --
rm: cannot remove ‘pids’: No such file or directory
rm: cannot remove ‘5QEM.log’: No such file or directory
rm: cannot remove ‘sock’: No such file or directory
rm: cannot remove ‘8BVT.log’: No such file or directory
rm: cannot remove ‘lf4N.log’: No such file or directory
rm: cannot remove ‘Jf8F.log’: No such file or directory
rm: cannot remove ‘H1UG.log’: No such file or directory
rm: cannot remove ‘sNbx.log’: No such file or directory
rm: cannot remove ‘D30J.log’: No such file or directory
rm: cannot remove ‘_yj1.log’: No such file or directory
rm: cannot remove ‘Tz9c.log’: No such file or directory
rm: cannot remove ‘ur0M.log’: No such file or directory
rm: cannot remove ‘pX6o.log’: No such file or directory
rm: cannot remove ‘8P_i.log’: No such file or directory
rm: cannot remove ‘kBX_.log’: No such file or directory
rm: cannot remove ‘n4Ot.log’: No such file or directory
rm: cannot remove ‘VVdY.log’: No such file or directory
rm: cannot remove ‘T1QJ.log’: No such file or directory
rm: cannot remove ‘Zdeo.log’: No such file or directory
rm: cannot remove ‘5ejy.log’: No such file or directory
rm: cannot remove ‘dQEL.log’: No such file or directory

出力が何を意味するのかわかりませんが、何も削除されないことがわかりました。私は直接サブファイル(サブフォルダのファイルではない)を削除することにのみ興味があります。

ベストアンサー1

検索を使用する:

これにより、現在のディレクトリの最新のファイルとフォルダを除くすべてのファイルが削除され、要求されたサブディレクトリではなく、直接フォルダの最新のファイルのみが確認されます。

find . -maxdepth 1 ! -path .  ! -wholename `find . -maxdepth 1  -printf '%T+ %p\n' | sort -n | tail -1 | cut -d " " -f2` -exec rm -rf {} \;

フォルダを削除せずにファイルのみを削除するには、次を使用します。-type f

find . -maxdepth 1 -type f  ! -path .  ! -wholename `find . -maxdepth 1  -printf '%T+ %p\n' | sort -n | tail -1 | cut -d " " -f2`  -exec rm -rf {} \;

例:

$ touch {1..100}
$ echo "hello" > 89
$ find . -maxdepth 1 -type f  ! -path .  ! -wholename `find . -maxdepth 1  -printf '%T+ %p\n' | sort -n | tail -1 | cut -d " " -f2`  -exec rm -rf {} \;
$ ls
89

おすすめ記事