Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get second last field from a cut command

Tags:

unix

awk

cut

I have a set of data as input and need the second last field based on deleimiter. The lines may have different numbers of delimiter. How can I get second last field ?

example input

text,blah,blaah,foo this,is,another,text,line 

expected output

blaah text 
like image 409
Archit Jain Avatar asked Jul 14 '13 21:07

Archit Jain


People also ask

How do I see the last second line of a file in Linux?

To look at the last few lines of a file, use the tail command. tail works the same way as head: type tail and the filename to see the last 10 lines of that file, or type tail -number filename to see the last number lines of the file.

How do we display the last second line of a file?

Use the tail command to write the file specified by the File parameter to standard output beginning at a specified point. This displays the last 10 lines of the accounts file. The tail command continues to display lines as they are added to the accounts file.


2 Answers

Got a hint from Unix cut except last two tokens and able to figure out the answer :

cat datafile | rev | cut -d '/' -f 2 | rev 
like image 54
Archit Jain Avatar answered Sep 23 '22 09:09

Archit Jain


Awk is suited well for this:

awk -F, '{print $(NF-1)}' file 

The variable NF is a special awk variable that contains the number of fields in the current record.

like image 29
Chris Seymour Avatar answered Sep 25 '22 09:09

Chris Seymour