0

I'm having trouble doing something very simple with awk. I'd like to print the last field, followed by another field.

Input file looks like this:

03 Oct 22,  Southern ,Mad,WIN,Gro,,33.10
03 Oct 22,  Mpd ,Mad,WIN,Auto,-208.56,
23 Sep 22,  Thank  ,n/a,WIN,,-97.93,

This way round works fine:

$ awk -F',' '{print "first " $6 " and then " $7}' input.csv
first  and then 33.10
first -208.56 and then
first -97.93 and then

But when I swap the fields over I get the strangest result:

$ awk -F',' '{print "first " $7 " and then " $6}' input.csv
and then 0
and then -208.56
and then -97.93

I must be missing something really simple. What on earth is going on?

$ awk --version
GNU Awk 5.1.0, API: 3.0 (GNU MPFR 4.1.0, GNU MP 6.2.1)
mdarwin
  • 1,684
  • 7
  • 28
  • 72
  • Please show output of this command: `file input.csv` – Cyrus Oct 07 '22 at 19:53
  • your input file contains windows/dos line endings (`\r\n`) so after printing `$7` you have a `\r` which moves the cursor back to the beginning of the line before printing `and then $6`; the easy solution is to remove the `\r` characters (eg, `dos2unix input.csv` - only has to be run once as this updates the file), or modify your code to remove the `\r` (eg, `{ gsub(/\r/,""); print ...}`) – markp-fuso Oct 07 '22 at 19:59
  • See: [awk and newline after final column](https://stackoverflow.com/q/34162239/3776858) – Cyrus Oct 07 '22 at 19:59
  • fwiw, something like `head -3 input.csv | od -c` should show the sequence `\r \n` at the end of each line – markp-fuso Oct 07 '22 at 20:01

1 Answers1

0

Only suggestion I have is to update awk. It works perfectly fine on my MacBook - with this version:

awk --version GNU Awk 5.1.1, API: 3.1 (GNU MPFR 4.1.0, GNU MP 6.2.1)

AlanW
  • 19
  • 2