디렉토리 트리에서 가장 오래된 파일부터 최신 파일까지 대화식으로 각 파일을 삭제합니다.

디렉토리 트리에서 가장 오래된 파일부터 최신 파일까지 대화식으로 각 파일을 삭제합니다.

1단계에서는 디렉토리 트리에서 가장 오래된 파일을 '찾기'하려고 하는데 다음과 같이 해결했습니다.이 질문.

xargs이제 가장 오래된 것부터 최신 것까지 대화식으로 삭제하는 데 사용하고 싶습니다 .

이것이 find -type f -printf '%T+ %p\n' | sort | xargs -0 -d '\n' rm -i작동하지 않기 때문에. 다른 게시물에서 봤지만 find . -type f -print0 | xargs -0 ls -rt추가해도 xargs작동하지 않습니다.

pi@raspberrypi:/usr/share/doc/samba$ find . -type f -print0 | xargs -0 ls -rt | xargs -0  -d '\n' rm -i
    rm: remove write-protected regular file ‘./examples/LDAP/samba.schema.oc.IBM-DS’? rm: remove write-protected regular file ‘./examples/LDAP/samba-schema-netscapeds5.x.README’? rm: remove write-protected regular file ‘./examples/LDAP/samba-schema.IBMSecureWay’? rm: remove write-protected regular file ‘./examples/LDAP/samba.schema.gz’? rm: remove write-protected regular file ‘./examples/LDAP/samba-schema-FDS.ldif.gz’? rm: remove write-protected regular file ‘./examples/LDAP/samba.schema.at.IBM-DS.gz’? rm: remove write-protected regular file ‘./examples/LDAP/samba-nds.schema.gz’? rm: remove write-protected regular file ‘./examples/LDAP/samba.ldif.gz’? rm: remove write-protected regular file ‘./examples/LDAP/ol-schema-migrate.pl.gz’? rm: remove write-protected regular file ‘./examples/LDAP/get_next_oid’? rm: remove write-protected regular file ‘./README.Debian’? rm: remove write-protected regular file ‘./TODO.Debian’? rm: remove write-protected regular file ‘./NEWS.Debian.gz’? rm: remove write-protected regular file ‘./copyright’? rm: remove write-protected regular file ‘./changelog.Debian.gz’? rm: remove write-protected regular file ‘./examples/LDAP/README’?

이는 권한 문제가 아니라는 점에 유의하세요. /usr/share/doc/samba실제 파일 이름을 게시하지 않기 위해 예제로 사용했습니다 .

웹을 검색해 보니 빈 파일 문자를 처리하고 대화형인 재귀적(전체 트리) 스크립트를 찾을 수 없었습니다. 그래서 이걸 만들었어요. 모든 유형의 특수 문자를 처리할 수는 없습니다. 따라서 어떤 개선이라도 받아들여질 것입니다.

#!/bin/bash
find -type f -printf '%T+ %p\n' | sort | head -n 3 > /tmp/1
cut -c32- /tmp/1 | awk '{print "rm -i", "\""$_"\""}'/tmp/2
bash /tmp/2

답변1

귀하의 스크립트에서 볼 수 있는 유일한 문제 문자는 "및 줄 바꿈입니다. 파일 이름의 줄 바꿈에 대해 너무 걱정할 필요는 없습니다.

$$예를 들어 파일 이름에 를 사용하여 다른 임시 파일 이름을 사용할 수 있습니다 .

그러면 개선 사항은 다음과 같습니다.

#!/bin/bash
TMP1=/tmp/file1.$$
TMP2=/tmp/file2.$$
find -type f -printf '%T+ %p\n' | sort | head -n 3 > $TMP1
cat $TMP1 | sed 's/"/\\"/g;s/[^ ]* //;s/^/rm -i "/;s/$/\"/' >$TMP2
bash $TMP2
rm -f $TMP1 $TMP2

파일 이름의 따옴표를 처리해야 합니다. (참고: 스크립트에는 여전히 몇 가지 문제가 있습니다. 하지만 자신의 집 환경에서 이 작업을 수행하는 것은 괜찮습니다. 그리고 대문자로 된 TMP는 권장되지 않지만 어쨌든 그렇게 합니다.)

참고: xargs -p파일 이름에 공백이 있으면 작동하지 않습니다.

답변2

거의 다 왔어요.

이것은 원하는 작업을 수행하고 파일 이름의 공백을 처리합니다.

find -type f -printf '%T+ %p\n' | sort | cut -c32- | xargs -p -n1 -d '\n' rm

-p, --interactive: 각 명령줄을 실행하고 터미널에서 줄을 읽을지 여부를 사용자에게 묻습니다. 응답이 y 또는 Y로 시작하는 경우에만 명령줄을 실행하세요.

-n max-args, --max-args=max-args: 명령줄당 최대 max-args 인수를 사용합니다.

-d delim입력 항목은 지정된 문자로 종료됩니다.

관련 정보