How to find the last field using 'cut'

2019-01-10 00:04发布

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?

标签: linux bash cut
10条回答
祖国的老花朵
2楼-- · 2019-01-10 00:39

There are multiple ways. You may use this too.

echo "Your string here"| tr ' ' '\n' | tail -n1
> here

Obviously, the blank space input for tr command should be replaced with the delimiter you need.

查看更多
3楼-- · 2019-01-10 00:40

the following implements A friend's suggestion

#!/bin/bash
rcut(){

  nu="$( echo $1 | cut -d"$DELIM" -f 2-  )"
  if [ "$nu" != "$1" ]
  then
    rcut "$nu"
  else
    echo "$nu"
  fi
}

$ export DELIM=.
$ rcut a.b.c.d
d
查看更多
We Are One
4楼-- · 2019-01-10 00:42

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.

查看更多
Explosion°爆炸
5楼-- · 2019-01-10 00:43

Without awk ?... But it's so simple with awk:

echo 'maps.google.com' | awk -F. '{print $NF}'

AWK is a way more powerful tool to have in your pocket. -F if for field separator NF is the number of fields (also stands for the index of the last)

查看更多
登录 后发表回答