我编写了一个 awk 程序,它给出了我需要的结果。 查找以 130AB 开头的任何行:如果第二个字段包含数据,则将其移动到第 9 个字段
我的输入文件:
130DD2532||1|||1|
130AB00100501||20|17112023|17112023||N|||0||
130DD2532||1|||1|
130AB00100502||20|17112023|17112023||N|||0||
130DD2532||1|||1|
130AB00100112||20|17112023|17112023||N|||0||
130DD2532||1|||1|
130AB00100113|00100113|20|17112023|17112023||N|||0||
看最后一行
我的程序文件prog.awk:
/^130AB/ { if ($2==""){print $1"|"$2"|"$3"|"$4"|"$5"|"$6"|"$7"|"$8"|"$9"|"$10"|"$11"|"$12"|"$13"|"$14"|"$15} else { print $1"|""|"$3"|"$4"|"$5"|"$6"|"$7"|"$8"|"$2"|"$10"|"$11"|"$12"|"$13"|"$14"|"$15}; next; };
{ print; }
我的命令行:
awk -F "|" -f prog.awk myFile.txt > newFile.txt
结果:newFile.txt
130DD2532||1|||1|
130AB00100501||20|17112023|17112023||N|||0|||||
130DD2532||1|||1|
130AB00100502||20|17112023|17112023||N|||0|||||
130DD2532||1|||1|
130AB00100112||20|17112023|17112023||N|||0|||||
130DD2532||1|||1|
130AB00100113||20|17112023|17112023||N||00100113|0|||||
它工作正常,但我的 prog.awk 不应该更清晰吗? :-)
谢谢你的帮助
关于布·伊利亚
当前代码的一种替代方案:
$ cat prog.awk
BEGIN { FS=OFS="|" } # define input/output field delimiters
/^130AB/ { if ($2 != "") { $9=$2; $2="" } # if 2nd field not blank then redefine 2nd/9th fields
for (i=NF+1; i<=15; i++) $i="" # add additional blank fields until we have a total of 15 fields
}
1 # print current line
注意:我已将
-F"|"
移动到BEGIN
块中,因此这将更改命令行调用,例如:
$ awk -f prog.awk myFile.txt > newFile.txt
这会生成:
$ cat newFile.txt
130DD2532||1|||1|
130AB00100501||20|17112023|17112023||N|||0|||||
130DD2532||1|||1|
130AB00100502||20|17112023|17112023||N|||0|||||
130DD2532||1|||1|
130AB00100112||20|17112023|17112023||N|||0|||||
130DD2532||1|||1|
130AB00100113||20|17112023|17112023||N||00100113|0|||||