Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
607 views
in Technique[技术] by (71.8m points)

unix - Sort by third column leaving first and second column intact in Linux?

I need to sort a flat file by third column leaving first column intact [First column is already sorted] (in linux). (second column may change)

Example i/p file:-

b:di:wave
b:di12:red
b:di12:wave
b:di06:pir

Should look like:-

b:di06:pir
b:di12:red
b:di12:wave
bast:di:wave

I tried several sorting options but I could sort only by second column but not third.

Can someone please help ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

sort  -t: -k1,1 -k3 data.txt

gives:

bast:disp-san-d5-06:piranha 
bast:display-san-12:redbird
bast:display-san-07:waverider
bast:display-san-12:waverider

This will sort with the 1st field as primary key, and the 3rd field as secondary key splitting the line into fields by :

Details:

data.txt contains the 4 lines from your post.

You can specify multiple fields as sorting keys, see the man page

-k1,1 means sort on the first field (start at field 1 and end at field 1, otherwise it would continue using the rest of the line for determining the sort)

-k3 means sort on the 3rd field as secondary key. Since there are no other fields behind it is not necessary to specify -k3,3 but it wouldn't hurt either.

-t: means delimit fields in lines with the : character, otherwise blank is used by default

More information see this SO question Sorting multiple keys with Unix sort and the sort man page


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...