폴더의 최신 파일을 제외한 모든 파일을 삭제하는 방법은 무엇입니까? [복사]

폴더의 최신 파일을 제외한 모든 파일을 삭제하는 방법은 무엇입니까? [복사]

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

답변2

zsh 사용:

zsh -c 'rm ~/.forever/*.log(.om[2,-1])'

포장 풀기:

  • 기준선 글로브 사용~/.forever/*.log
  • 일반 파일만 선택( .)
  • o수정 시간을 기준으로 정렬합니다. m(이렇게 하면 최신 파일이 이전 파일 앞에 배치됩니다.)
  • 2이 정렬된 목록에서 마지막( )까지의 범위를 선택하세요. -1이렇게 하면 최신 파일인 요소 #1이 제외됩니다.
  • 그런 다음 전달된 파일 목록이 됩니다.rm

인용하다:

답변3

디렉터리에 이름을 나열 .forever하지만 rm한 수준 위의 명령을 실행합니다. 거기에 같은 이름을 가진 중요한 파일이 없기를 바랍니다.

이것을 스크립트에 넣으려면 cd파일을 삭제하려는 디렉토리에 직접 넣는 것이 가장 쉬운 방법이지만 xargs 호출에 디렉토리 이름을 추가하는 것도 옵션입니다.

물론 사용하지 않는 출력에 대한 경고 설명은 ls유효하지만, 귀하의 경우 파일 이름에 따라 이를 무시할 수도 있습니다.

관련 정보