LinuxQuestions.org
Help answer threads with 0 replies.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Linux Forums > Linux - Software
User Name
Password
Linux - Software This forum is for Software issues.
Having a problem installing a new program? Want to know which application is best for the job? Post your question in this forum.

Notices


Reply
  Search this Thread
Old 11-23-2007, 02:46 PM   #1
Robert S
Member
 
Registered: Oct 2006
Location: Canberra
Distribution: gentoo, debian
Posts: 63

Rep: Reputation: 15
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?
 
Old 11-23-2007, 02:59 PM   #2
ilikejam
Senior Member
 
Registered: Aug 2003
Location: Glasgow
Distribution: Fedora / Solaris
Posts: 3,109

Rep: Reputation: 97
Hi.

Yup. 'NF' contains the number of fields in the record, so
Code:
awk '{print $(NF-1)}'
will print the second last field.

Dave
 
Old 11-23-2007, 03:06 PM   #3
Robert S
Member
 
Registered: Oct 2006
Location: Canberra
Distribution: gentoo, debian
Posts: 63

Original Poster
Rep: Reputation: 15
Many thanks for the speedy answer. I'll use this forum more in the future for such questions!
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
BASH: rename an argument of the script sylvaticus Programming 2 05-21-2007 08:20 AM
-bash: /bin/: Argument list too long zeeshan673 Linux - General 4 02-22-2007 10:25 AM
bash: /bin/ls: Argument list too long. Workaround? Kropotkin Linux - General 3 02-28-2006 11:45 AM
bash: /bin/rm: Argument list too long? FiveFlat Linux - General 5 08-11-2004 11:29 PM
-bash: /bin/mv: Argument list too long balanagireddy Linux - General 2 07-27-2004 11:19 PM

LinuxQuestions.org > Forums > Linux Forums > Linux - Software

All times are GMT -5. The time now is 04:14 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration