Get the characters after the last index of a substring from a string

。_饼干妹妹 提交于 2021-01-16 12:36:17

问题


I have a string which is an output of another command. I only need the end of this string to display. The separator string is "." (dot and space), and I need the string after the last index of ".".

How can I do this in Bash?


回答1:


try this:

your cmd...|sed 's/.*\. //'

this works no matter how many "dot" or "dot and space" do you have in your input. it takes the string after the last "dot and space"




回答2:


If the string is in a variable:

$ foo="header. stuff. more stuff"
$ echo "${foo##*. }"
more stuff

If there are multiple instances of ". " (as in my example) and you want everything after the first occurrence, instead of the last, just use one #:

$ echo "${foo#*. }"
stuff. more stuff



回答3:


Awk is elegant weapon...for a more civilized age:

[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

In this case NF is the awk variable for "Number of fields" and this construct says "print the entry in highest number of fields found" so if the size of your input changes from one line to the next you're still going to get the last one.

You can also do math:

[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~]$

(Yes, this is 3 years late for the OP, but one of my cow-orkers pointed me to this page today for something we were working on, so I thought I'd drop this here in case others are looking too.)




回答4:


Try this:

echo "This is a sentence. This is another sentence" | rev | cut -d "." -f1 | rev

The rev reverses the output. The -d specifies the delimiter, breaking everything up into fields. The -f specifies the fields you want to use. We can select f1, because we reversed the data. We don't need to know how many fields there are in total. We just need to know the first. At the end, we reverse it again, to put it back in the right order.



来源:https://stackoverflow.com/questions/15548277/get-the-characters-after-the-last-index-of-a-substring-from-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!