2015-04-03 84 views
-1

我必須整理文件。當我使用排序時,每行只需要第一個單詞。例如。我有這些字符。如何在BASH中使用排序來排序文件?

能夠在各地大量早期的加速作用下廣告

我執行

排序file.txt的

輸出是:

能夠在各地加速作用早豐以下廣告

如果我只有一列,排序工作。問題是什麼?

+2

從'man'頁面的機器使用它像:'排序 - 排序文本文件的行「。 'sort'在**行**上工作,而不是列。 – 2015-04-03 15:04:03

+0

我知道,但我的排序工作在列**而不是行**。 – 2015-04-03 15:07:47

+0

你的真實檔案也是一班嗎?如果您有多行輸入,您希望如何組織輸出? – gboffi 2015-04-03 15:27:17

回答

1

你可以嘗試這樣的事情:

tr " " "\n" < file.txt | sort | tr "\n" " " > newfile.txt 

輸出到newfile.txt:

 
a able abundance accelerated acting ad around early following 
+0

我無法創建新文件。我試圖使用sed,它有幫助。但是我有數字問題。我怎樣才能避免排序數字(爲eaxmple日期)? – 2015-04-03 15:18:17

+0

@ user3465780排序有很多選項,請查看手冊頁'man sort' – dan08 2015-04-03 15:21:30

1

你有幾個選項:

要在行排序的話,你可以使用sed來替換帶有新行的空格,然後將其傳送到sort

sed 's/ /\n/g' file.txt | sort 

排序在特定的列中使用awk打印的列然後通過管道,爲sort

awk {print $2} | sort 

我用這個有很多的數據文件時,我還沒有找到一種方法,排序後得到整條線。

+0

我用過這個! :)謝謝:) – 2015-04-03 16:52:05

+1

@ user3465780,如果你使用這個答案,你應該接受它:http://stackoverflow.com/help/someone-answers – 2015-04-03 16:56:17

1

你必須把每個單詞在單獨一行:

tr -s '[:blank:]' '\n' < file.txt | sort | paste -d" " -s 
a able abundance accelerated acting ad around early following   
1

以防萬一你想在AA多行文件中的每一行進行排序,下面的一行代碼可以做到這一點你

python2 -c"print '\n'.join(' '.join(sorted(l.split())) for l in open('FILE'))" 

如果上面看起來有用,你可以增加你的~/.bashrc

csort(){ python2 -c"print '\n'.join(' '.join(sorted(l.split()))for l in open('$1'))";} 

後來在

csort FILE 

python命令是最好的解釋爆炸命令行這樣

with open('FILE') as f:     # f is a file object 
    for line in f:      # iterating on a f.o. returns lines 
     words = line.split()   # by default splits on white space 
     print " ".join(sorted(words)) # sorted returns a sorted list 
             # ' '.join() joins the list elements with spaces