简体   繁体   中英

Find largest file by name in bash script

I have json files with names

logtext.json
logtext.json.1
logtext.json.2
logtext.json.3

How to find file with greatest number with bash script? In this case output should be "logtext.json.3"

Use sort --version-sort

-V, --version-sort
    natural sort of (version) numbers within text
find . -name "*.json*" | sort --version-sort | tail -n 1


If no name sort needs to be done, just use ls

ls | sort --version-sort | tail -n 1


tail -n 1 limits the output to just 1 line

$ ls file.json file.json.1 file.json.15 file.json.3 $ find . -name "*.json*" | sort --version-sort | tail -n 1 ./file.json.15

I place an answer here without parsing the output of ls because this is a non-portable bad practice.

See: https://unix.stackexchange.com/q/128985/310674

printf '%s\n' *.json* \
  | sort --reverse --version-sort \
  | head --lines=1
  • printf '%s\\n' *.json* : Produces a newline delimited stream of all files matching the *.json* pattern. This is portable and much more reliable than parsing the output of ls .
  • sort --reverse --version-sort : Sorts the stream lines in reverse order, with version number sorting rules. This will place the highest version at the first line.
  • head --lines=1 : Prints the first line of the stream. Here it is preventing the read of the whole stream until the last line, since it stops at the first line.

If you use the GNU version of the utilities, you can process a null delimited list rather than a newline delimited list. This will allow handling of file names witch can contain spaces , newlines or other non-printable characters.

printf '%s\0' *.json* \
  | sort --reverse --version-sort --zero-terminated \
  | head --lines=1 --zero-terminated

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM