我有一个字符串,它是另一个命令的输出.我只需要显示此字符串的结尾.分隔符字符串是" .
"(点和空格),我需要在" .
" 的最后一个索引之后的字符串.
我怎么能在Bash中这样做?
che*_*ner 27
如果字符串在变量中:
$ foo="header. stuff. more stuff"
$ echo "${foo##*. }"
more stuff
Run Code Online (Sandbox Code Playgroud)
如果有多个"."实例(如我的例子中所示)并且您想要在第一次出现之后的所有内容而不是最后一次,只需使用一个#
:
$ echo "${foo#*. }"
stuff. more stuff
Run Code Online (Sandbox Code Playgroud)
Ken*_*ent 22
试试这个:
your cmd...|sed 's/.*\. //'
Run Code Online (Sandbox Code Playgroud)
无论您在输入中有多少"点"或"点和空格",这都有效.最后一个 "点和空格" 后面的字符串
试试这个:
echo "This is a sentence. This is another sentence" | rev | cut -d "." -f1 | rev
Run Code Online (Sandbox Code Playgroud)
该rev
反转输出.在-d
指定的分隔符,打破一切成田.在 -f
指定的字段要使用.我们可以选择f1,因为我们反转了数据.我们不需要知道总共有多少个字段.我们只需知道第一个.最后,我们再次对其进行反转,以正确的顺序将其恢复.
Awk是优雅的武器......对于更文明的年龄:
[cpetro01@h ~]$ echo "this. is. my. string. of. some. arbitrary. length" | awk -F'. ' ' { print $NF } '
length
[cpetro01@h ~]$ echo "this. is. my. string. of. some" | awk -F'. ' ' { print $NF } '
some
Run Code Online (Sandbox Code Playgroud)
在这种情况下,NF是"字段数"的awk变量,这个结构显示"在找到的最大字段数中打印条目",所以如果输入的大小从一行变为下一行,你仍然会得到最后一个.
你也可以做数学:
[cpetro01@h~]$ echo "this. is. my. string. of. some. arbitrary. length" | awk -F'. ' ' { print $(NF-2) } '
some
[cpetro01@h~]$ echo "this. is. my. string. of. some. arbitrary. length" | awk -F'. ' ' { print $(NF-3) } '
of
[cpetro01@h~]$
Run Code Online (Sandbox Code Playgroud)
(是的,对于OP来说这已经晚了3年,但是我的一位牛犊今天指出我正在处理的这个页面,所以我想我会把它放在这里以防万一其他人也在看.)