Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWK not printing output file separator OFS

Tags:

bash

awk

Input

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

Expected output

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

Current output

15.01.2018Payment sent-500.00
20.12.2017Payment received10.40

Does one see the problem in my command?

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

Thank you

like image 711
jjk Avatar asked Jan 22 '18 17:01

jjk


2 Answers

I don't understand why you're surprised that when you print $1$2$3 there's no OFS between them but I also don't understand why you were trying to use the logic in your script at all instead of just:

$ 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
like image 111
Ed Morton Avatar answered Nov 09 '22 09:11

Ed Morton


Following awk may help you in same.

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

Output will be as follows.

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

Explanation: Adding explanation for above code too now.

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.
like image 1
RavinderSingh13 Avatar answered Nov 09 '22 10:11

RavinderSingh13