简体   繁体   中英

Unix sort rows based on semicolon

I try to sort the following file:

$ cat testfile
ZBOX-BATCH-SAMEDI;CMC10
ZBOX-BATCH-SAMEDI_D1;HEB05
ZBOX-BATCH-SAMEDI;BMD15
ZBOX-BATCH-SAMEDI_D3;HEB03
ZBOX-BATCH-SAMEDI_D3_M1;ODP47
ZBOX-BATCH-SAMEDI_D1_M1;TER23
ZBOX-BATCH-SAMEDI_D3;HEB02
ZBOX-BATCH-SAMEDI_D1;HEB02
ZBOX-BATCH-SAMEDI;DEA11
ZBOX-BATCH-SAMEDI;DEA11A

And I get:

$ sort testfile
ZBOX-BATCH-SAMEDI;BMD15
ZBOX-BATCH-SAMEDI;CMC10
ZBOX-BATCH-SAMEDI_D1;HEB02
ZBOX-BATCH-SAMEDI_D1;HEB05
ZBOX-BATCH-SAMEDI_D1_M1;TER23
ZBOX-BATCH-SAMEDI_D3;HEB02
ZBOX-BATCH-SAMEDI_D3;HEB03
ZBOX-BATCH-SAMEDI_D3_M1;ODP47
ZBOX-BATCH-SAMEDI;DEA11
ZBOX-BATCH-SAMEDI;DEA11A

However, I was expecting:

ZBOX-BATCH-SAMEDI;BMD15
ZBOX-BATCH-SAMEDI;CMC10
ZBOX-BATCH-SAMEDI;DEA11
ZBOX-BATCH-SAMEDI;DEA11A
...

That is, I want all the rows with the string ZBOX-BATCH-SAMEDI before the first semicolon to come first, then the ones with ZBOX-BATCH-SAMEDI_D1 , etc.

I looked man sort and I tried different options like -g and -k with -t , but I didn't manage. How can I do it?

Just tell sort that the delimiter is ; and you want to sort based on the second column:

sort -t";" -k2 file

It returns:

ZBOX-BATCH-SAMEDI;BMD15
ZBOX-BATCH-SAMEDI;CMC10
ZBOX-BATCH-SAMEDI;DEA11
ZBOX-BATCH-SAMEDI;DEA11A
ZBOX-BATCH-SAMEDI_D1;HEB02
ZBOX-BATCH-SAMEDI_D3;HEB02
ZBOX-BATCH-SAMEDI_D3;HEB03
ZBOX-BATCH-SAMEDI_D1;HEB05
ZBOX-BATCH-SAMEDI_D3_M1;ODP47
ZBOX-BATCH-SAMEDI_D1_M1;TER23

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