AWK从csv连接下两行
我正在使用以下命令连接下一行,但希望连接下两行AWK从csv连接下两行,awk,Awk,我正在使用以下命令连接下一行,但希望连接下两行 awk -v OFS=', ' 'NR==1{first=$0} NR>1{print prev, $0} {prev=$0} END{print prev, first}' test.csv test.csv rabbit cat dog turtle sheep cow 结果: rabbit, cat cat, dog dog, turtle turtle, sheep sheep, cow cow, rabbit 预期结果: ra
awk -v OFS=', ' 'NR==1{first=$0} NR>1{print prev, $0} {prev=$0} END{print prev, first}' test.csv
test.csv
rabbit
cat
dog
turtle
sheep
cow
结果:
rabbit, cat
cat, dog
dog, turtle
turtle, sheep
sheep, cow
cow, rabbit
预期结果:
rabbit, cat, dog
cat, dog, turtle
dog, turtle, sheep
turtle, sheep, cow
sheep, cow, rabbit
cow, rabbit, cat
如果您有任何帮助,我们将不胜感激。请尝试以下内容,用GNU awk编写。仅使用所示样品进行书写和测试
awk -v RS= -v OFS=', ' '
{
for(i=1;i<=(NF-1);i++){
printf("%s %s %s %s\n",$i,OFS $(i+1),OFS $(i+2),i==(NF-1)?$1:"")
}
}
END{
print $NF,$1,$2
}
' Input_file
说明:增加对以上内容的详细说明
awk -v RS= -v OFS=', ' ' ##Starting awk program from here.
{
for(i=1;i<=(NF-1);i++){ ##Running for loop from 1to till 2nd last element of line.
printf("%s %s %s %s\n",$i,OFS $(i+1),OFS $(i+2),i==(NF-1)?$1:"") ##Printing current field, OFS next field and next to next field and checking condition if i==NF-1 then print 1st field else print nothing.
}
}
END{ ##Starting END block for this code from here.
print $NF,$1,$2 ##Printing last field then 1st and 2nd field here.
}
' Input_file ##Mentioning Input_file name here.
只需将完整文件读入内存,然后操作列:
$ awk -v OFS="," -v n=3 '{a[NR-1]=$0}END{for(i=0;i<NR;++i) for(j=0;j<n;++j) printf "%s%s",a[(i+j)%NR], (j==n-1?ORS:OFS)}' file