2017-05-24 35 views
1

從文本文件級聯兩列從同一文件

文件

a d 
b e 
c f 

如何在製表符分隔柱連接成一列

a 
b 
c 
d 
e 
f 

Now我使用awk將列輸出到兩個文件,然後使用cat連接。但是必須有更好的一行命令?

回答

2

一個廣義的辦法

$ f() { awk '{print $'$1'}' file; }; f 1; f 2 

a 
b 
c 
d 
e 
f 

如果文件選項卡或許分隔簡單地用cut(的paste逆運算)

$ cut -f1 file.t; cut -f2 file.t 
+0

剪切方法似乎是連接文件的最快方法。我將在一個擁有64百萬行的文本文件上運行,因此速度很快。 – rommedahl

0

這個簡單的awk命令應該做的工作:

awk '{print $1; s=s $2 ORS} END{printf "%s", s}' file 
a 
b 
c 
d 
e 
f 
+1

恕我直言,我認爲OP的要求輸出是差異因爲OP需要首先打印1美元,然後打印2美元。 – RavinderSingh13

+0

謝謝@ RavinderSingh13,我忽略了那部分。現在已經糾正了。 – anubhava

0

您可以使用進程替換;這將消除爲每列創建文件的需要。

$ cat file 
a d 
b e 
c f 
$ cat <(awk '{print $1}' file) <(awk '{print $2}' file) 
a 
b 
c 
d 
e 
f 
$ 

OR

按照註釋你可以合併多個命令及其輸出重定向到一個不同的文件是這樣的:

$ cat file 
a d 
b e 
c f 
$ (awk '{print $1}' file; awk '{print $2}' file) > output 
$ cat output 
a 
b 
c 
d 
e 
f 
$ 
+1

在這種情況下,'cat'看起來沒用:'(awk'{print $ 1}'文件; awk'{print $ 2}'文​​件)'應該足夠了。 –

+0

子殼也不需要,只是'awk ..; awk ..'會做。 – karakfa

-1

如果您使用notepadd ++,你可以全部替換tab值與newl enter image description here ine char「\ r \ n」

+1

他詢問有關使用bash腳本(請參閱標籤)。 –

+0

此外,這將交錯列。 –

-1

另一種方法:

for i in $(seq 1 2); do 
    awk '{print $'$i'}' file 
done 

輸出:

a 
b 
c 
d 
e 
f 
+1

只有在輸入發生排序時纔有效,但在一般情況下不適用。 –

+0

不,這不是,這就是爲什麼它用一種排序管道 – Unwastable

+0

它交錯然後排序。假設輸入看起來像'a b \ nc d'。期望的輸出是'a \ nc \ nb \ nd',但是你的輸出是'a \ nb \ nc \ nd'。 –

0

試:不讀取文件兩次或沒有任何外部電話s的任何其他命令,只有一個awk來拯救。另外考慮到你的Input_file與所示樣本相同。

awk '{VAL1=VAL1?VAL1 ORS $1:$1;VAL2=VAL2?VAL2 ORS $2:$2} END{print VAL1 ORS VAL2}' Input_file 

說明:只需在創建一個名爲VAL1變量,它包含$ 1值,並保持在它自己的價值串聯,VAL2將有$ 2'S價值,不斷串接在它自己的價值。在awk的END部分,打印VAL1和VAL2的值。與;

0

您可以組合的bash命令來獲取單個流:

​​

使用過程中替換,如果你想要的是,如果它是一個單一的文件:

$ txt=$(awk '{print $1}' file; awk '{print $2}' file) 
$ echo "$txt" 
a 
b 
c 
d 
e 
f 

或爲一個Bash while循環:

$ while read -r line; do echo "line: $line"; done < <(awk '{print $1}' file; awk '{print $2}' file) 
line: a 
line: b 
line: c 
line: d 
line: e 
line: f