Can someone please explain why we need to set ORS in below awk code?

Question: Write a command to print the fields in a text file in reverse order?

awk 'BEGIN {ORS=""} { for(i=NF;i>0;i--) print $i," "; print "\n"}' filename

I was thinking it should be (what is the need to set ORS="" ? )-

awk 'BEGIN { for(i=NF;i>0;i--) print $i," "; print "\n"}' filename

Hi, the default ORS (output record separator) is set to '\n' . If it were left to its default value, then the output of each print command would appear on a different line, whereas the intention appears to be to print al fields on the same line, but in reverse order, separated by two spaces.

--
The creator of the script could have accomplished the same using printf , which is more intended for this purpose and then ORS would not need to be set:

awk '{for(i=NF;i>0;i--) printf "%s  " $i; print ""}'
1 Like

@Scrutinizer that explains the code well. Thank you very much :slight_smile:

and I think we also need a \n for expected output :slight_smile:

awk '{for(i=NF;i>0;i--) printf "%s  ",$i; print "\n"}'
1 Like

You're welcome. Yes I meant to write print "" , not print . I will correct it in my post..
One could also use: printf "\n" or printf ORS .

1 Like