How to print last two columns using awk?

You can make use of variable NF which is set to the total number of fields in the input record.

Up vote 3 down vote favorite 1 share g+ share fb share tw.

All I want is the last two columns printed. Thanks I am surprised this question wasn't yet asked. Bash awk link|improve this question asked Nov 29 '10 at 14:59vehomzzz3,44153076 92% accept rate.

You can make use of variable NF which is set to the total number of fields in the input record: awk '{print $(NF-1),"\t",$NF}' file this assumes that you have at least 2 fields.

You need a comma - since we are being picky today: space concatenates fields, comma separates fields in a print statement. That will merge the two fields – jim mcnamara Nov 29 '10 at 15:06 Now you're printing "field-OFS-tab-OFS-field". It should be awk '{print $(NF-1) "\t" $NF}' file or awk '{print $(NF-1), $NF}' file or awk 'BEGIN{OFS="\t"} {print $(NF-1), $NF}' file.

– Dennis Williamson Nov 29 '10 at 17:06 @Dennis: I'm sorry I didn't get it. – codaddict Nov 29 '10 at 17:25.

Awk '{print $NF-1, $NF}' inputfile Note: this works only if at least two columns exist. On records with one column you will get a spurious "-1 column1.

$NF-1 will not work. – codaddict Nov 29 '10 at 15:02 Try and see. It does work Solaris 9 awk & nawk.

The alternative is $(NF-1) – jim mcnamara Nov 29 '10 at 15:04 1 Here you go: ideone.com/FQCuF – codaddict Nov 29 '10 at 15:08 thank, $(NF-1) worked. – vehomzzz Nov 29 '10 at 15:09 @coaddict - I'm guessing you haven't worked with different awk implementations. Old awks behaviors have been (maybe erroneously) brought forward.

I do not have gawk to test against -- which is probably what you are referencing. So I don't know for sure why your comment came abnput. Linux awk out of the box usually is gawk.

I will test and post back. Meanwhile try Soalris or HPUX or DGX or whatever to see what I mean by old awk. – jim mcnamara Nov 29 '10 at 15:14.

Using gawk gets the problem: gawk '{ print $NF-1, $NF}' filename 1 2 2 3 -1 one -1 three # cat filename 1 2 2 3 one one two three I just put gawk on Solaris 10 M4000: So, gawk is the cuplrit on the $NF-1 vs. $(NF-1) issue. Next question what does POSIX say? Per: opengroup.org/onlinepubs/009695399/utili... There is no direction one way or the other.

Not good. Gawk implies subtraction, other awks imply field number or subtraction. Hmm.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions