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

  • 本文关键字:打印 字段 选择性 awk
  • 更新时间 :
  • 英文 :


想阅读第一行,然后打印 $1、$3、$4 作为第一行,然后打印 $2、$3、$4 作为第二行,依此类推......

输入.txt

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

预期产量.txt

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

寻找您的建议!!

使用 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:查找第一个字段、第二个字段、rest ;打印 1st/rest - 打印 2nd/rest

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

在一个步骤中,给出更新的所需输出:

$ 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]}

通过 sed,

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

最新更新