简体   繁体   English

重击获得最后一句

[英]Bash get last sentence in line

assume, we got the following variable containing a string: 假设,我们得到了以下包含字符串的变量:

text="All of this is one line. But it consists of multiple sentences. Those are separated by dots. I'd like to get this sentence."

I now need the last sentence "I'd like to get this sentence.". 现在,我需要最后一句话“我想得到这句话”。 I tried using sed: 我尝试使用sed:

echo "$text" | sed 's/.*\\.*\\.//'

I thought it would delete everything up to the pattern .*. 我以为它将删除模式.*. . It doesn't. 没有。

What's the issue here? 这里有什么问题? I'm sure this can be resolved rather fast, unfortunatly I did not find any solution for this. 我敢肯定,这可以很快解决,但是很遗憾,我没有找到任何解决方案。

Using awk you can do: 使用awk,您可以执行以下操作:

awk -F '\\. *' '{print $(NF-1) "."}' <<< "$text"

I'd like to get this sentence.

Using sed: 使用sed:

sed -E 's/.*\.([^.]+\.)$/\1/' <<< "$text"

 I'd like to get this sentence.

Don't forget the built-in 不要忘记内置

echo "${text##*. }"

This requires a space after the full stop, but the pattern is easy to adapt if you don't want that. 这需要在句号后留一个空格,但是如果您不想这样,则很容易适应该模式。

As for your failed attempt, the regex looks okay, but weird. 至于您失败的尝试,正则表达式看起来还可以,但很奇怪。 The pattern \\.*\\. 模式\\.*\\. looks for zero or more literal periods followed by a literal period, ie effectively one or more period characters. 查找零个或多个文字周期,后跟一个文字周期,即一个或多个句点字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM