Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I know how to select a field from a line using the cut command. For instance, given the following data:

a,b,c,d,e
f,g,h,i,j
k,l,m,n,o

This command:

cut -d, -f2 # returns the second field of the input line

Returns:

b
g
l

My question: How can I select the second field counting from the end? In the previous example, the result would be:

d
i
n
share|improve this question
    
See stackoverflow.com/q/4304917/789593 –  N.N. Feb 13 '13 at 16:54

2 Answers 2

up vote 9 down vote accepted

Reverse the input before and after cut with rev:

<infile rev | cut -d, -f2 | rev

Output:

d
i
n
share|improve this answer

Try doing this with :

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

Or using :

perl -F, -lane 'print $F[-2]' file.txt

Or using (thanks manatwork) :

ruby -F, -lane 'print $F[-2]' file.txt

Or using bash (thanks manatwork) :

while IFS=, read -ra d; do echo "${d[-2]}"; done < file.txt

Or using :

cat file.txt |
python -c $'import sys\nfor line in sys.stdin:\tprint(line.split(",")[-2])'
share|improve this answer
1  
bash not needs fixed column count for this: while IFS=, read -ra d; do echo "${d[-2]}"; done < file.txt. –  manatwork Feb 13 '13 at 15:03
1  
BTW, your third solution also works if you change perl with ruby. –  manatwork Feb 13 '13 at 15:08
    
Thanks, ruby added, bash edited. –  sputnick Feb 13 '13 at 15:39
1  
If the 4th field may start with - or (depending on the environment, shell, or how the shell was compiled), may contain backslash characters, then echo is not an option. Why do you need to con`cat`enate file.txt with nothing before feeding it to python!?. You need read -A instead of read -a in ksh93 and zsh. Negative subscripts work in zsh but only in recent versions of ksh93 and bash. In older versions, you can use ${d: -2:1} –  Stéphane Chazelas Feb 13 '13 at 16:01
2  
@StephaneChazelas, I think you mean ${d[@]: -2:1} in your last sentence. –  manatwork Feb 15 '13 at 8:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.