2011-06-09 26 views
26

我正在尋找解決此問題的最簡單方法。我有一個巨大的數據集,我不能加載到Excel這類格式使用unix工具和多列進行排序

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

我想要做的排序是這樣,從最小到最大,基於數的。

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

不知道的最好的辦法是做什麼的,我想使用awk來切換列和做一個排序,但我遇到了麻煩,這樣做。

幫我個忙,請

+0

是的,你可以導入這種類型的數據到Excel中,如果你導入爲文本,然後指定「|」作爲分隔符。 – 2011-06-10 13:50:25

回答

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

應該這樣做。現場分離器和備用鍵選擇

+2

'+ 2'中'+'的用途是什麼? – brandizzi 2011-06-09 16:06:37

+1

將焦點從第一個分隔組移到第二個分隔組。 – zellio 2011-06-09 16:14:34

+4

@brandizzi:習慣。舊版本的排序使用+和 - 來標示要排序的列和不排序的列。 GNU排序使用不需要它的另一種技術(但也不會在+上禁用) – 2011-06-09 16:17:19

7

你有那種試圖-n

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

,你可以使用awk切換列太

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

結合awk和排序:

每條評論

,如果你在句子中

$ 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 

,當然你可以把它重定向到一個新的文件有一個數字:

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

這隻有在句子中沒有數字的情況下才有效。 – zellio 2011-06-09 15:59:29

+0

的確如此,我正在脫離他複製的例子。 – matchew 2011-06-09 16:01:15

2

排序號,更換分離器,並使用搶第二組分類。

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

嘗試這類命令:

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

您通常不需要貓將文件發送到一個過濾器。也就是說,你可以使用排序過濾器。

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

這樣使用|來排序MyDataSet.txt文件。字符作爲字段分隔符並根據第二個字段(數字)進行數字排序。