IT박스

Linux의 디렉토리에서 최신 파일 가져 오기

itboxs 2020. 6. 9. 22:16
반응형

Linux의 디렉토리에서 최신 파일 가져 오기


디렉토리에서 가장 최근의 단일 파일을 반환하는 명령을 찾고 있습니다.

ls에 제한 매개 변수가 표시되지 않습니다 ...


ls -Art | tail -n 1

매우 우아하지는 않지만 작동합니다.


ls -t | head -n1

이 명령은 실제로 현재 작업 디렉토리의 최신 수정 파일을 제공합니다.


이것은 재귀 버전입니다 (즉, 특정 디렉토리 또는 하위 디렉토리에서 가장 최근에 업데이트 된 파일을 찾습니다)

find $DIR -type f -printf "%T@ %p\n" | sort -n | cut -d' ' -f 2- | tail -n 1

편집 : Kevin이 제안한 -f 2-대신 사용하십시오.-f 2


나는 사용한다:

ls -ABrt1 --group-directories-first | tail -n1

폴더를 제외한 파일 이름 만 알려줍니다.


ls -lAtr | tail -1

다른 솔루션에는로 시작하는 파일이 포함되어 있지 않습니다 '.'.

이 명령에는 '.'and 가 포함 되며 '..', 원하는대로 또는 아닐 수도 있습니다.

ls -latr | tail -1


dmckee의 답변을 기반으로 한 단락 변형 :

ls -t | head -1

신뢰성에 대한 참고 사항 :

개행 문자는 파일 이름에서와 마찬가지로 유효하므로 / 기반 과 같은 행에 의존하는 솔루션 에는 결함이 있습니다.headtail

GNU ls에서 다른 옵션은 --quoting-style=shell-always옵션과 bash배열 을 사용하는 것입니다 .

eval "files=($(ls -t --quoting-style=shell-always))"
((${#files[@]} > 0)) && printf '%s\n' "${files[0]}"

( 숨겨진 파일도 고려 하려면 -A옵션을 추가하십시오 ls).

일반 파일 (디렉토리, fifo, 장치, 심볼릭 링크, 소켓 무시)로 제한하려면 GNU를 사용해야합니다 find.

bash 4.4 이상 (for readarray -d) 및 GNU coreutils 8.25 이상 (for cut -z) :

readarray -t -d '' files < <(
  LC_ALL=C find . -maxdepth 1 -type f ! -name '.*' -printf '%T@/%f\0' |
  sort -rzn | cut -zd/ -f2)

((${#files[@]} > 0)) && printf '%s\n' "${files[0]}"

또는 재귀 적으로 :

readarray -t -d '' files < <(
  LC_ALL=C find . -name . -o -name '.*' -prune -o -type f -printf '%T@%p\0' |
  sort -rzn | cut -zd/ -f2-)

여기서 가장 번거로운 작업을 피하는 zsh대신 글로브 한정자 를 사용하는 것이 가장 좋습니다 bash.

현재 디렉토리의 최신 일반 파일 :

printf '%s\n' *(.om[1])

숨겨진 것 포함 :

printf '%s\n' *(D.om[1])

두 번째 최신 :

printf '%s\n' *(.om[2])

심볼릭 링크 해결 후 파일 수명 확인 :

printf '%s\n' *(-.om[1])

재귀 적으로 :

printf '%s\n' **/*(.om[1])

또한 완료 시스템 ( compinit및 co)을 사용 Ctrl+Xm하면 최신 파일로 확장되는 완료자가됩니다.

그래서:

vi Ctrl+Xm

최신 파일을 편집하게하십시오 (를 누르기 전에 어떤 파일을 볼 수도 있습니다 Return).

vi Alt+2Ctrl+Xm

두 번째로 작은 파일입니다.

vi * .cCtrl+Xm

최신 c파일.

vi * (.)Ctrl+Xm

최신 일반 파일 (디렉토리 나 fifo / 장치가 아님) 등.


찾기 / 정렬 솔루션은 전체 파일 시스템과 같이 파일 수가 실제로 커질 때까지 훌륭하게 작동합니다. 가장 최근 파일을 추적하려면 대신 awk를 사용하십시오.

find $DIR -type f -printf "%T@ %p\n" | 
awk '
BEGIN { recent = 0; file = "" }
{
if ($1 > recent)
   {
   recent = $1;
   file = $0;
   }
}
END { print file; }' |
sed 's/^[0-9]*\.[0-9]* //'

나는 단지 파일 이름을 제공하고 다른 명령을 호출하지 않기 때문에 echo *(om[1])( zsh구문)을 좋아한다 .


I personally prefer to use as few not built-in bash commands as I can (to reduce the number of expensive fork and exec syscalls). To sort by date the ls needed to be called. But using of head is not really necessary. I use the following one-liner (works only on systems supporting name pipes):

read newest < <(ls -t *.log)

or to get the name of the oldest file

read oldest < <(ls -rt *.log)

(Mind the space between the two '<' marks!)

If the hidden files are also needed -A arg could be added.

I hope this could help.


Recursively:

find $1 -type f -exec stat --format '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head

using R recursive option .. you may consider this as enhancement for good answers here

ls -arRtlh | tail -50

ls -t -1 | sed '1q'

Will show the last modified item in the folder. Pair with grep to find latest entries with keywords

ls -t -1 | grep foo | sed '1q'

try this simple command

ls -ltq  <path>  | head -n 1

If you want file name - last modified, path = /ab/cd/*.log

If you want directory name - last modified, path = /ab/cd/*/


Presuming you don't care about hidden files that start with a .

ls -rt | tail -n 1

Otherwise

ls -Art | tail -n 1

All those ls/tail solutions work perfectly fine for files in a directory - ignoring subdirectories.

In order to include all files in your search (recursively), find can be used. gioele suggested sorting the formatted find output. But be careful with whitespaces (his suggestion doesn't work with whitespaces).

This should work with all file names:

find $DIR -type f -printf "%T@ %p\n" | sort -n | sed -r 's/^[0-9.]+\s+//' | tail -n 1 | xargs -I{} ls -l "{}"

This sorts by mtime, see man find:

%Ak    File's  last  access  time in the format specified by k, which is either `@' or a directive for the C `strftime' function.  The possible values for k are listed below; some of them might not be available on all systems, due to differences in `strftime' between systems.
       @      seconds since Jan. 1, 1970, 00:00 GMT, with fractional part.
%Ck    File's last status change time in the format specified by k, which is the same as for %A.
%Tk    File's last modification time in the format specified by k, which is the same as for %A.

So just replace %T with %C to sort by ctime.


Finding the most current file in every directory according to a pattern, e.g. the sub directories of the working directory that have name ending with "tmp" (case insensitive):

find . -iname \*tmp -type d -exec sh -c "ls -lArt {} | tail -n 1" \;

ls -Frt | grep "[^/]$" | tail -n 1

I needed to do it too, and I found these commands. these work for me:

If you want last file by its date of creation in folder(access time) :

ls -Aru | tail -n 1  

And if you want last file that has changes in its content (modify time) :

ls -Art | tail -n 1  

참고URL : https://stackoverflow.com/questions/1015678/get-most-recent-file-in-a-directory-on-linux

반응형