Bash得到最后一句话

时间:2016-05-20 16:39:07

标签: bash awk sed grep last-occurrence

假设我们得到了包含字符串的以下变量:

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."

我现在需要最后一句“我想得到这句话。”我尝试使用sed:

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

我认为它会删除模式.*.以外的所有内容。它没有。

这里有什么问题?我确信这可以解决得相当快,不幸的是我没有找到任何解决办法。

2 个答案:

答案 0 :(得分:3)

使用awk你可以这样做:

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

I'd like to get this sentence.

使用sed:

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

 I'd like to get this sentence.

答案 1 :(得分:2)

别忘了内置的

echo "${text##*. }"

这需要在完全停止后留出一个空格,但如果你不想要那个模式很容易适应。

至于你失败的尝试,正则表达式看起来没问题,但很奇怪。模式\.*\.查找零个或多个文字句点,后跟一个文字句点,即有效的一个或多个句点字符。

相关问题