2014-12-23 46 views
-2

行想讀出的第一行然後打印$ 1,$ 3,圖4 $作爲第一行然後$ 2,$ 3,$ 4的第二行等等...要打印選擇性列字段成

INPUT.TXT

10,20,abc,def 
70,40,xxx,yyy 
30,50,mno,pqr 

預計Output.txt的

10,abc,def 
20,abc,def 
70,xxx,yyy 
40,xxx,yyy 
30,mno,pqr 
50,mno,pqr 

尋找您的建議!

+0

我不確定你爲什麼接受不做什麼的答案你要。 –

回答

3

用awk天真的方法:只打印你想要什麼,用逗號作爲輸入/輸出字段分隔符:

~$ awk 'BEGIN{FS=OFS=","}{print $1,$3,$4;print $2,$3,$4}' f.txt 
10,abc,def 
20,abc,def 
70,xxx,yyy 
40,xxx,yyy 
30,mno,pqr 
50,mno,pqr 

隨着SED:找到第一場,第二,休息;打印第一/休息 - 打印第二/休息

~$ sed -e 's/\([^,]*\),\([^,]*\),\(.*\)/\1,\3\n\2,\3/' f.txt 
10,abc,def 
20,abc,def 
70,xxx,yyy 
40,xxx,yyy 
30,mno,pqr 
50,mno,pqr 
1

通過sed的,

$ sed 's/^\([^,]*\),\([^,]*\),\([^,]*\),\([^,]*\)$/\1,\3,\4\n\2,\3,\4/g' file 
10,abc,def 
20,abc,def 
70,xxx,yyy 
40,xxx,yyy 
30,mno,pqr 
50,mno,pqr 
+0

通常我讚揚替代解決方案,但是這個只是讓我頭疼:-) – paxdiablo

+0

使用'-r',你不需要轉義'()',所以你得到'sed -r's/^([^ ,] *),([^,] *),([^,] *),([^,] *)$/\ 1,\ 3,\ 4 \ n \ 2,\ 3,\ 4 /克'' – Jotne

+0

是的,但是在OSX中的sed將不支持'-r' –

2

在一個步驟中,使更新的希望的輸出:

$ awk 'BEGIN {FS = OFS = ","} FNR==NR {a[$1] = $0; next} $1 in a {print $0, a[$1]} $2 in a {print $0, a[$2]}' ref.txt input.txt 
10,20,abc,def,10,red 
10,20,abc,def,20,blue 

說明:

FNR==NR # only true when processing the first file (ref.txt) 
{ 
    a[$1] = $0; # build index for lines in ref.txt using $1 as the key 
    next   # skip any further actions going to directly to next line of ref.txt 
} 

# (By here we know we are processing past the first file, input.txt in this case) 
# If the first field exists in our index, print the line along with the corresponding line from ref.txt: 
$1 in a {print $0, a[$1]} 

# repeat for the second field: 
$2 in a {print $0, a[$2]}