将选择性列字段打印到行中

时间:2014-12-23 09:34:09

标签: awk

想要读取第一行然后打印$ 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

寻找你的建议!!

3 个答案:

答案 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:找到第一个字段,第二个,休息; print 1st / rest - print 2nd / rest

~$ 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 :(得分: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]}

答案 2 :(得分: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