LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   Bash script: how do I select second-to-last argument in a list (https://www.linuxquestions.org/questions/linux-software-2/bash-script-how-do-i-select-second-to-last-argument-in-a-list-601961/)

Robert S 11-23-2007 02:46 PM

Bash script: how do I select second-to-last argument in a list
 
I am trying to write a bash script that pulls out the second-to-last argument in a list of fields in a text file. The number of fields is variable for each line - eg.

arg1 arg2 arg3 arg4 arg5
arg1 arg2 arg3 arg4 arg5 arg6
arg1 arg2 arg3 arg4

In this case I'd like the script to pull out:

arg4
arg5
arg3

I can use awk to print out the first n arguments ie (cat filename | awk '{print @2}'), but is there an easy way to pull out a certain number of arguments from the end?

ilikejam 11-23-2007 02:59 PM

Hi.

Yup. 'NF' contains the number of fields in the record, so
Code:

awk '{print $(NF-1)}'
will print the second last field.

Dave

Robert S 11-23-2007 03:06 PM

Many thanks for the speedy answer. I'll use this forum more in the future for such questions!


All times are GMT -5. The time now is 08:23 AM.