Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the last field using 'cut'

Tags:

linux

bash

cut

Without using sed or awk, only cut, how do I get the last field when the number of fields are unknown or change with every line?

like image 918
noobcoder Avatar asked Mar 29 '14 04:03

noobcoder


People also ask

Which of the following command is used to extract the last field from a file and assume that file is a comma delimited?

You can use the cut command just as awk command to extract the fields in a file using a delimiter.

How do I print the last column in Linux?

“awk” is a very powerful Linux command that can be used with other commands as well as with other variables. This command is essentially used to read the content of a file.


2 Answers

You could try something like this:

echo 'maps.google.com' | rev | cut -d'.' -f 1 | rev 

Explanation

  • rev reverses "maps.google.com" to be moc.elgoog.spam
  • cut uses dot (ie '.') as the delimiter, and chooses the first field, which is moc
  • lastly, we reverse it again to get com
like image 130
zedfoxus Avatar answered Oct 17 '22 19:10

zedfoxus


Use a parameter expansion. This is much more efficient than any kind of external command, cut (or grep) included.

data=foo,bar,baz,qux last=${data##*,} 

See BashFAQ #100 for an introduction to native string manipulation in bash.

like image 24
Charles Duffy Avatar answered Oct 17 '22 18:10

Charles Duffy