Setup:
$ cat files.txt
file1234
other44234
something34142
carrot123
One convoluted chain of commands:
$ sed -nE 's/^(.*[^0-9])([0-9]+)$/\2 \1\2/p' files.txt | sort -nr | head -1 | awk '{print $2}'
other44234
But once we pull awk
into the mix there's really no need for anything else, eg:
awk '{ if (match($0,/([0-9]+)$/)) { # if we find a string of numbers at the end of the line (aka filename)
sfx=substr($0,RSTART) # strip off the number and ...
if (sfx>max) { # if larger than the previous find then ...
max=sfx # make note of the new largest number and ...
fname=$0 # grab copy of current line (aka filename)
}
}
}
END { if (fname) print fname} # if fname is non-blank then print to stdout
' files.txt
This also generates:
other44234
Or doing the whole thing in bash
with a regex and the BASH_REMATCH[]
array:
regex="^.*[^0-9]([0-9]+)$"
fname=""
max=0
while read -r f
do
[[ "${f}" =~ $regex ]] &&
[[ "${BASH_REMATCH[1]}" -gt "${max}" ]] &&
max="${BASH_REMATCH[1]}" &&
fname="${f}"
done < files.txt
This generates:
$ typeset -p fname
declare -- fname="other44234"