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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Reverse the input before and after cut with rev:
<infile rev | cut -d, -f2 | rev
Output:
d i n
Method 2
Try doing this with awk :
awk -F, '{print $(NF-1)}' file.txt
Or using perl :
perl -F, -lane 'print $F[-2]' file.txt
Or using ruby (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 python :
cat file.txt |
python -c $'import sysnfor line in sys.stdin:tprint(line.split(",")[-2])'
Method 3
Using sed:
sed -E 's/^([^,]*,)*([^,]*)(,[^,]*){1}$/2/' infile
Output:
d i n
Explanation
([^,]*,)*matches any number of non-comma charecter followed by a comma, i.e. any number of columns.([^,]*)matches a column.(,[^,]*){1}matches one column at the end, if you change the quantifier{1}to{2}it matches the third column from the end etc.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0