假设,我们得到以下包含字符串的变量:
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/.*\.*\.//'
我以为它会删除模式之前的所有内容
.*.
。事实并非如此。
这里有什么问题吗?我确信这个问题可以很快得到解决,不幸的是我没有找到任何解决方案。
使用 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.
不要忘记内置
echo "${text##*. }"
这需要在句号后有一个空格,但如果您不想这样,该模式很容易适应。
至于您失败的尝试,正则表达式看起来不错,但很奇怪。模式
\.*\.
查找零个或多个字面句点,后跟一个字面句点,即有效的一个或多个句点字符。