2016-01-13 65 views
0

文件,我有這樣兩個文件,yolo.txtbar.txt的bash重定向到沒有工作

yolo.txt:

a 
b 
c 

跳回到bar.txt:

c 

我有以下命令,它可以得到我想要的輸出:

$ cat yolo.txt bar.txt | sort | uniq -u | sponge 
a 
b 

但是當我添加重定向(>)語句,輸出的變化:

$ cat yolo.txt bar.txt | sort | uniq -u | sponge > yolo.txt && cat yolo.txt 
c 

我預想的輸出保持不變,我很困惑。請幫幫我。

+1

你知道海綿,但你不知道爲什麼它是必要的?這是怎麼來的? –

回答

3

> yolo.txt shell重定向發生在任何命令運行之前。特別是,在執行cat yolo.txt bar.txt之前,shell會打開yolo.txt以編寫並截斷它。所以到時候cat打開yolo.txt,yolo.txt是空的。因此bar.txt中的c行是唯一的,因此uniq -u會將其傳遞。

我想你想用sponge來避免這個問題,因爲這就是sponge的用途。但是你錯誤地使用了它。這是正確的用法:

cat yolo.txt bar.txt | sort | uniq -u | sponge yolo.txt && cat yolo.txt 

請注意,我只是通過輸出文件名sponge作爲命令行參數,而不是使用shell重定向。