4

I'm not sure I understand the NF variable in awk.

My example file (test) contains one line:

1 2 3 4 5

The following works as expected:

awk '{print $1,$NF}' test
1 5

But the next example does not (i.e. the reverse):

awk '{print $NF,$1}' test
 1

What am I missing here? I can print $NF by itself, or after $1, but not before.

Chris
  • 43
  • 3
  • 1
    It works fine for me, can you check once if you have carriage characters on those? by doing `cat -v file` once? – RavinderSingh13 Feb 20 '18 at 15:37
  • 2
    Unable to reproduce: `echo "1 2 3 4 5" | awk '{print $NF,$1}'` works fine – JNevill Feb 20 '18 at 15:37
  • `dos2unix myFile` may fix it. While you have presented a good minimal test case, don't get into the habit of using `test`, as there is a shell command by the same name. Good luck. – shellter Feb 20 '18 at 15:38

1 Answers1

1

Since it works fine for me, I am suspecting it could be carriage characters which could cause this issue, if this is the case then try following:

1- Check if carriage characters are present in any Input_file by doing:

cat -v Input_file

2- In case you find any carriage characters in your Input_file then you could remove them by doing following:

tr -d '\r' < Input_file > temp_file  &&  mv temp_file  Input_file
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93