Awk 将选定的列字段打印到行中
希望阅读第一行,然后打印$1、$3、$4作为第一行,然后打印$2、$3、$4作为第二行,依此类推 Input.txtAwk 将选定的列字段打印到行中,awk,Awk,希望阅读第一行,然后打印$1、$3、$4作为第一行,然后打印$2、$3、$4作为第二行,依此类推 Input.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=","}
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:查找第一个字段,第二个字段,其余字段;第一次打印/休息-第二次打印/休息
~$ 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
通过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
在一个步骤中,给出更新后的所需输出:
$ 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]}
通常情况下,我对其他解决方案表示欢迎,但这一方案让我很头疼:-)使用
-r
,你不需要逃避()
,因此你得到了sed-r/^([^,]*),([^,]*),([^,]*),([^,]*)$/\1,3,4\n\2,3,4/g'
yep,但是OSX中的sed不支持-r
,我不知道你为什么接受了一个不符合你要求的答案。