不使用sed或awk,只cut,当字段的数量未知或随每一行变化时,我如何得到最后一个字段?


当前回答

下面实现一个朋友的建议

#!/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

其他回答

使用参数展开。这比包括cut(或grep)在内的任何外部命令都要有效得多。

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

参见BashFAQ #100,了解bash中本地字符串操作的介绍。

这是唯一可能的解决方案,只使用切割:

回声“s.t.r.i.n.g。”| cut -d'。- f2 - [repeat_following_part_forever_or_until_out_of_memory:] | cut -d'。- f2 -

使用此解决方案,字段的数量确实可以是未知的,并且随时变化。但是,由于行长不能超过LINE_MAX字符或字段(包括新行字符),那么任意数量的字段永远不能作为该解决方案的实际条件。

是的,一个非常愚蠢的解决方案,但我认为这是唯一符合标准的解决方案。

这是不可能只使用切割。下面是使用grep的方法:

grep -o '[^,]*$'

用逗号替换其他分隔符。

解释:

-o (--only-matching) only outputs the part of the input that matches the pattern (the default is to print the entire line if it contains a match). [^,] is a character class that matches any character other than a comma. * matches the preceding pattern zero or more time, so [^,]* matches zero or more non‑comma characters. $ matches the end of the string. Putting this together, the pattern matches zero or more non-comma characters at the end of the string. When there are multiple possible matches, grep prefers the one that starts earliest. So the entire last field will be matched.

完整的例子:

如果我们有一个叫data。csv的文件包含

one,two,three
foo,bar

然后输出grep -o '[^,]*$' < data.csv

three
bar

为这个老问题添加一个方法只是为了好玩:

$ cat input.file # file containing input that needs to be processed
a;b;c;d;e
1;2;3;4;5
no delimiter here
124;adsf;15454
foo;bar;is;null;info

$ cat tmp.sh # showing off the script to do the job
#!/bin/bash
delim=';'
while read -r line; do  
    while [[ "$line" =~ "$delim" ]]; do
        line=$(cut -d"$delim" -f 2- <<<"$line")
    done
    echo "$line"
done < input.file

$ ./tmp.sh # output of above script/processed input file
e
5
no delimiter here
15454
info

除了bash,只使用cut。 我想,还有回声。

没有awk ? 但是用awk很简单:

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

AWK是一个更强大的工具,可以放在你的口袋里。 -F if用于字段分隔符 NF是字段的数量(也表示最后一个字段的索引)