开发者

Sorting with unix tools and multiple columns

开发者 https://www.devze.com 2023-03-12 06:21 出处:网络
I am looking for the easiest way to solve this problem. I have a huge data set that i cannot load into excel of this type of format

I am looking for the easiest way to solve this problem. I have a huge data set that i cannot load into excel of this type of format

This is a sentence|10
This is another sentence|5
This is the last sentence|20

What I want to do is sort this from le开发者_StackOverflowast to greatest based on the number.

cat MyDataSet.txt | tr "|" "\t" | ???

Not sure what the best way is to do this, I was thinking about using awk to switch the columns and the do a sort, but I was having trouble doing it.

Help me out please


sort -t\| -k +2n dataset.txt

Should do it. field separator and alternate key selection


You usually don't need cat to send the file to a filter. That said, you can use the sort filter.

sort -t "|" -k 2 -n MyDataSet.txt

This sorts the MyDataSet.txt file using the | character as field separator and sorting numerically according to the second field (the number).


have you tried sort -n

$ sort -n inputFile
This is another sentence|5
This is a sentence|10
This is the last sentence|20

you could switch the columns with awk too

$ awk -F"|" '{print $2"|"$1}' inputFile
10|This is a sentence
5|This is another sentence
20|This is the last sentence

combining awk and sort:

$ awk -F"|" '{print $2"|"$1}' inputFile | sort -n
5|This is another sentence
10|This is a sentence
20|This is the last sentence

per comments

if you have numbers in the sentence

$ sort -n -t"|" -k2 inputFile
This is another sentence|5
This is a sentence|10
This is the last sentence|20
this is a sentence with a number in it 2|22

and of course you could redirect it to a new file:

$ awk -F"|" '{print $2"|"$1}' inputFile | sort -n > outFile


Try this sort command:

sort -n -t '|' -k2 file.txt


Sort by number, change the separator and grab the second group using sort.

sort -n -t'|' -k2 dataset.txt
0

精彩评论

暂无评论...
验证码 换一张
取 消