AWK不打印输出文件分隔符OFS

时间:2018-01-22 17:34:37

标签: bash awk

输入

15.01.2018;Payment sent;;500.00;;
20.12.2017;Payment received;10.40;;;

预期输出

15.01.2018;Payment sent;-500.00
20.12.2017;Payment received;10.40

当前输出

15.01.2018Payment sent-500.00
20.12.2017Payment received10.40

我的命令中是否有人看到问题?

awk 'BEGIN{OFS=";";FS=";"} {print match($4, /[^ ]/) ? $1$2$3"-"$4 : $1$2$3}' < in.csv > out.csv

谢谢

3 个答案:

答案 0 :(得分:3)

我不明白为什么当你打印$1$2$3时它们之间没有OFS但我也不明白你为什么试图在你的脚本中使用逻辑而不仅仅是:

$ awk 'BEGIN{FS=OFS=";"} {print $1, $2, ($3=="" ? "-"$4 : $3)}' file
15.01.2018;Payment sent;-500.00
20.12.2017;Payment received;10.40

答案 1 :(得分:1)

关注awk可能对您有帮助。

awk -F";" '$4~/[0-9]/{$4="-"$4}{gsub(/;+/,";");sub(/;$/,"")}  1' OFS=";"  Input_file

输出如下。

15.01.2018;Payment sent;-500.00
20.12.2017;Payment received;10.40

说明: 现在也为上述代码添加说明。

awk -F";" '         ##Setting field separator as semi colon here.
$4~/[0-9]/{         ##Checking condition here if 4th field is having digit in it, if yes then do following:
  $4="-"$4          ##Adding a dash(-) before 4th field value here.
}
{
  gsub(/;+/,";");   ##By Globally substitution method Removing multiple semi colons occurrences with single semi colon here, as per OP shown output.
  sub(/;$/,"")      ##By using normal substitution method replacing semi colon which comes at last of line with NULL here.
}
1                   ##awk works on method of condition{action}, so here I am making condition TRUE and NOT mentioning any action so default print will happen.
' OFS=";" Input_file##Setting OFS(Output field separator) as semi colon here and mentioning Input_file name here too.

答案 2 :(得分:0)

awk '{sub(/sent;;/,"sent;-")sub(/;;+/,"")}1' file

15.01.2018;Payment sent;-500.00
20.12.2017;Payment received;10.40

第一个子元素将分号更改为破折号,第二个子元素在最后一个零之后删除分号。