1832979 Members
3524 Online
110048 Solutions
New Discussion

Re: Simple awk problem

 
SOLVED
Go to solution
Belinda Dermody
Super Advisor

Simple awk problem

I have a file with many lines and each line has variable number of fields. I always need the next to last field for a report. How can I get the next to last field of each line in variable fields line.
9 REPLIES 9
Sridhar Bhaskarla
Honored Contributor
Solution

Re: Simple awk problem

Hi,

Try this way

cat file|awk '{print $(NF-1)}'

-Sri
You may be disappointed if you fail, but you are doomed if you don't try
Rodney Hills
Honored Contributor

Re: Simple awk problem

NF is number of fields on the record. You can then do the following-

awk '{NN=NF-1; print $NN}' yourfile

HTH

-- Rod Hills

There be dragons...
James R. Ferguson
Acclaimed Contributor

Re: Simple awk problem

Hi James:

# awk '{print $(NF-1)}' filename

For example:

# echo "1 2 3\na b\nh e l l o !"|awk '{print $(NF-1)}'

...prints:

2
a
o

Regards!

...JRF...
Belinda Dermody
Super Advisor

Re: Simple awk problem

Thanks for the quick reply and they both work, 10 points to the first and 9 for the others.
James R. Ferguson
Acclaimed Contributor

Re: Simple awk problem

Hi:

Do you *really* consider the timestamps of the three replies to differ?

...JRF...
Belinda Dermody
Super Advisor

Re: Simple awk problem

Ah come on Jim, I gave you 9 points even though your answer was the same Sridhar. At least I give points to everyone that responds. I see a lot of responses where there is none or just to one. I even assign points that do not even come close to the subject.
Robin Wakefield
Honored Contributor

Re: Simple awk problem

To be honest, Jim's was the "better" solution, as you should always take advantage of a command's capabilities to open a file rather than use cat/pipe and therefore waste a process.

Rgds, Robin
Belinda Dermody
Super Advisor

Re: Simple awk problem

Robin, your are correct, but I wasn't using the cat in my process, it was at the end of a ps command that was piped into grep -v |piped into a sort and then finally the awk to print the next to last field.
Sridhar Bhaskarla
Honored Contributor

Re: Simple awk problem

I often use awk as receiver to commands and that sense was carried in the post too.

Since you mentioned that you had the file, JRF's solution stands as the most correct one though this is all about the idea of using NF-1.

With the time stamps, you can understand that everyone responded at the same time and that's what JRF was mentioning about.

You are appreciated for your promptness in assigning the points.

-Sri
You may be disappointed if you fail, but you are doomed if you don't try