使用unix工具和多列进行排序

jos*_*iti 26 unix sorting bash awk

我正在寻找解决这个问题的最简单方法.我有一个巨大的数据集,我无法加载到这种格式的excel

This is a sentence|10
This is another sentence|5
This is the last sentence|20
Run Code Online (Sandbox Code Playgroud)

我想要做的是根据数字从最小到最大排序.

cat MyDataSet.txt | tr "|" "\t" | ???
Run Code Online (Sandbox Code Playgroud)

不知道最好的方法是做什么,我正在考虑使用awk来切换列并进行排序,但是我无法做到这一点.

请帮帮我

Set*_*son 35

sort -t\| -k +2n dataset.txt
Run Code Online (Sandbox Code Playgroud)

应该这样做.字段分隔符和备用密钥选择

  • @brandizzi:习惯.较旧版本的排序使用+和 - 来表示要排序的列和不排序的列.GNU排序使用不需要它的不同技术(但也不会在+上进行barf) (4认同)
  • `+ 2`中`+`的目的是什么? (2认同)
  • @Alexander:"n"表示数字.换句话说,假设第二个参数是一个数字,以便5在10之前排序.当在我使用它的上下文中使用它时,它仅将n参数应用于参数2.这是无关紧要的,因为只有一个排序键,但是对于更复杂的命令,它可能很重要. (2认同)

Jav*_*r C 13

您通常不需要cat将文件发送到过滤器.也就是说,您可以使用排序过滤器.

sort -t "|" -k 2 -n MyDataSet.txt
Run Code Online (Sandbox Code Playgroud)

这将使用|对MyDataSet.txt文件进行排序 字符作为字段分隔符,并根据第二个字段(数字)进行数字排序.


mat*_*hew 7

你试过排序-n吗?

$ sort -n inputFile
This is another sentence|5
This is a sentence|10
This is the last sentence|20
Run Code Online (Sandbox Code Playgroud)

你也可以用awk切换列

$ awk -F"|" '{print $2"|"$1}' inputFile
10|This is a sentence
5|This is another sentence
20|This is the last sentence
Run Code Online (Sandbox Code Playgroud)

结合awk和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
Run Code Online (Sandbox Code Playgroud)

每条评论

如果你的句子中有数字

$ 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
Run Code Online (Sandbox Code Playgroud)

当然你可以将它重定向到一个新文件:

$ awk -F"|" '{print $2"|"$1}' inputFile | sort -n > outFile
Run Code Online (Sandbox Code Playgroud)