繁体   English   中英

sed:保留包含块模式的每个单词的最后一个块

[英]sed: keep last chunk of each word containing chunk pattern

愿意只保留最后一段包含点的单词(仍然保留不包含模式的单词):

sed 似乎只匹配最后一个词:

$ echo "Here this.is.a.start is a very.nice.String  that.is.the.end yes " | sed 's/.*[ ]\([^ ]*\.\)\([^ ]*\)[ ].*/\2/g'
end

$ echo "Here this.is.a.start is a very.nice.String  that.is.the.end yes " | sed 's/.*[ ]\([^ ]*\.\)\([^ ]*\)[ ].*/\1/g'
that.is.the.

我应该怎么做才能得到这个结果? :

echo "Here this.is.a.start is a very.nice.String  that.is.the.end yes " | sed s\\\g
Here start is a String  end yes

用 \w 表示一个词:

echo "Here this.is.a.start is a very.nice.String  that.is.the.end yes " |
 sed -E 's/\w*\.//g'

您可以使用

sed -E 's/([^ .]+\.)+([^ .]+)/\2/g'
sed -E 's/([^[:space:].]+\.)+([^[:space:].]+)/\2/g'

[:space:]将考虑任何空格,而不仅仅是一个空格字符。

查看在线sed演示

echo "     * {@link my.tailor.is.rich but( ther.is.a.hole.in.my.pants )}. " | \
 sed -E 's/([^ .]+\.)+([^ .]+)/\2/g'
# => "     * {@link rich but( pants )}. "

细节

  • ([^.]+\.)+ - 一次或多次出现
    • [^.]+ - 除了空格和点之外的任何一个或多个字符
    • \. - 一个点
  • ([^.]+) - 第 2 组:除空格和点之外的任何一个或多个字符。

仅匹配您要替换的内容。 .*[ ]匹配所有内容- 有什么用。 您只想替换something.dot.something - 匹配尽可能小。

echo "Here this.is.a.start is a very.nice.String  that.is.the.end yes " |
 sed 's/\(^\| \)[^ ]*\.\([^ ]\)/\1\2/g'
  • \(^\| \)匹配行首或空格并记住它在\1
  • [^ ]*\. - 匹配任何文本后跟一个点
  • \([^ ]\) - 匹配任何文本并记住\2
$ s="Here this.is.a.start is a very.nice.String that.is.the.end yes " $ # if you know the characters that make up the words $ echo "$s" | sed -E 's/[a-z.]*\.//ig' Here start is a String end yes $ # a field based approach $ echo "$s" | awk '{for(i=1;i<=NF;i++) sub(/.*\./, "", $i)} 1' Here start is a String end yes

这可能对你有用(GNU sed):

sed -E 's/([^. ]+\.)+//g' file

全局删除一个或多个非句点/空格后跟句点的组。

暂无
暂无

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

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