How to sort text by last column?
This command
udisksctl status
with Ubuntu 20.04.3 gives:
MODEL REVISION SERIAL DEVICE
--------------------------------------------------------------------------
SanDisk Extreme 0001 AA010302161107080264 sdb
ATAPI DVD A DH17A3L 8H3D ATAPI_DVD_A_DH17A3L sr0
KINGSTON SA400S27230G S3Z40107 50016B7683B02C0B sda
Optiarc DVD RW AD-7580A 1.04 Optiarc_DVD_RW_AD-7580A sr0
HL-DT-STDVD-RAM GH22NS30 2.00 HL-DT-STDVD-RAM_GH22NS30 sr0
Floppy Drive fd0
Generic Flash Disk 8.07 162194AF sdc
The target is to sort by the last 3 characters in each line (after the header), giving:
Floppy Drive fd0
KINGSTON SA400S27230G S3Z40107 50016B7683B02C0B sda
SanDisk Extreme 0001 AA010302161107080264 sdb
Generic Flash Disk 8.07 162194AF sdc
Optiarc DVD RW AD-7580A 1.04 Optiarc_DVD_RW_AD-7580A sr0
ATAPI DVD A DH17A3L 8H3D ATAPI_DVD_A_DH17A3L sr0
HL-DT-STDVD-RAM GH22NS30 2.00 HL-DT-STDVD-RAM_GH22NS30 sr0
I got partial success with
udisksctl status | tail -n+3 | rev | sort -b -k1.1 | rev | grep 'sd\|hd\|fd\|sr\|st'
udisksctl status | tail -n+3
from bottom (tail) to line 3 thus cut out 2 line header:
MODEL REVISION SERIAL DEVICE
--------------------------------------------------------------------------
udisksctl status | tail -n+3 | rev |
Reverse, bring last characters in a line to the front of the line.
udisksctl status | tail -n+3 | rev | sort -b -k1.1
sort -b
= ignore leading blanks-k1.1
= sort via key first letter after ignored blanks
udisksctl status | tail -n+3 | rev | sort -b -k1.1 | rev
undo reverse
udisksctl status | tail -n+3 | rev | sort -b -k1.1 | rev | grep 'sd\|hd\|fd\|sr\|st'
Highlight with grep:
-
sd
Scsi Device -
hd
Hard Disk Drive -
fd
Floppy Drive -
sr
Scsi ROM, cdrom, dvd -
st
Scsi Tape Drive - ...
For simplicity focus on last 3 letters. The problem is how to do a sort to get:
fd0
sda
sdb
sdc
sr0
sr0
sr0
Because the problem as shown above is last 1 letter is sorted not last 3 letters:
fd0
sr0
sr0
sr0
sda
sdb
sdc
How can I sort by the last 3 characters in a line? (The lines have different lengths.)
Try this:
udisksctl status | awk '{ print $NF,$0 }' | sort -k1,1 -n | cut -f2- -d' '
That takes care also longer strings like nvme0n1
as sorting is done by last column, not a number of characters.
I don't have udiskctl, but tested by copying your list to a file sortof
, adding NVM drive to verify and catting the file:
pg@TREX:~/test$ cat sortof | awk '{ print $NF,$0 }' | sort -k1,1 -n | cut -f2- -d' '
HL-DT-STDVD-RAM GH22NS30 2.00 HL-DT-STDVD-RAM_GH22NS30 sr0 Floppy Drive fd0
KINGSTON SA400S27230G S3Z40107 50016B7683B02C0B nvme1p
KINGSTON SA400S27230G S3Z40107 50016B7683B02C0B sda
SanDisk Extreme 0001 AA010302161107080264 sdb
Generic Flash Disk 8.07 162194AF sdc
ATAPI DVD A DH17A3L 8H3D ATAPI_DVD_A_DH17A3L sr0
Optiarc DVD RW AD-7580A 1.04 Optiarc_DVD_RW_AD-7580A sr0
... so it should work also when you pipe the udiskctl output.