我正在尝试使用 awk 来格式化包含多行的文件。
文件内容:
ABC;0;1
ABC;0;0;10
ABC;0;2
EFG;0;1;15
HIJ;2;8;00
KLM;4;18;12
KLM;6;18;1200
KLM;10;18;14
KLM;1;18;15
Run Code Online (Sandbox Code Playgroud)
想要的结果:
ABC;0;1;10;2
EFG;0;1;15
HIJ;2;8;00
KLM;4;18;12;1200;14;15
Run Code Online (Sandbox Code Playgroud)
我正在使用下面的代码:
awk -F ";" '{
ligne= ligne $0
ma_var = $1
{getline
if($1 != ma_var){
ligne= ligne "\n" $0
}
else {
ligne= ligne";"NF
}
}
}
END {
print ligne
} ' ${FILE_IN} > ${FILE_OUT}
Run Code Online (Sandbox Code Playgroud)
目标是将下一行的第一列与当前行的第一列进行比较,如果匹配则将下一行的最后一列添加到当前行,并删除下一行,否则打印下一行。
亲切的问候,
与生活一样,根据已经发生的事情(上一行)做出决定比将要发生的事情(下一行)要容易得多。重新陈述您的要求the objective is to compare the first column of the current line to the first column the previous line, if it matches then add the last column of the current line to the previous line, and delete the current line, else print the current line.,实现它的代码变得相对简单:
$ cat tst.awk
BEGIN { FS=OFS=";" }
$1 == p1 { prev = prev OFS $NF; next }
{ if (NR>1) print prev; prev=$0; p1=$1 }
END { print prev }
$ awk -f tst.awk file
ABC;0;1;10;2
EFG;0;1;15
HIJ;2;8;00
KLM;4;18;12;1200;14;15
Run Code Online (Sandbox Code Playgroud)
如果您想getline再次使用,请确保在做出决定之前完全理解http://awk.freeshell.org/AllAboutGetline 上讨论的所有内容。