Reputation: 83
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"
Upvotes: 2
Views: 95
Reputation: 19545
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
Upvotes: 2
Reputation: 43964
-V, --version-sort
natural sort of (version) numbers within text
find . -name "*.json*" | sort --version-sort | tail -n 1
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
Upvotes: 3