How to sort the string which combined with string + numeric using bash script?
This is very similar to this question. The trouble is that you have an alphanumeric field that you are sorting on, and -n
doesn't treat that sensibly, however version sort (-V
) does. Thus use:
sort -V
Note that this feature is currently supported by the GNU, FreeBSD and OpenBSD sort implementations.
You can use a temporary sentinel character to delimit the number:
$ sed 's/\([0-9]\)/;\1/' log | sort -n -t\; -k2,2 | tr -d ';'
Here, the sentinel character is ';' - it must not be part of any filename you want to sort - but you can exchange the ';' with any character you like. You have to change the sed
, sort
and tr
part then accordingly.
The pipe works as follows: The sed
command inserts the sentinel before any number, the sort
command interprets the sentinel as field delimiter, sorts with the second field as numeric sort key and the tr
command removes the sentinel again.
And log
denotes the input file - you can also pipe your input into sed
.
If all your file names have the same prefix before the final numeric part, ignore it when sorting:
sort -k 1.20n
(20 is the position of the first digit. It's one plus the length of /home/files/profile
.)
If you have several different non-numeric parts, insert a sentinel.