linux - 使用 sed,在数字匹配之前只删除一个字符

标签 linux bash awk sed

我有一个这样的文本文件:

text-text-text-7.7.1-text
text-text-text-text-1.2.4-text
text-text-1.2.4-text

我希望将数字之前的字符替换为空格。所以预期的输出应该是

text-text-text 7.7.1-text
text-text-text-text 1.2.4-text
text-text 1.2.4-text

我如何使用 sed 做到这一点?

我试过使用 sed -E 's/-//g' 但它用空格替换了所有 -

text text text 7.7.1 text
text text text text 1.2.4 text
text text 1.2.4 text

以及 sed -E 's/-[0-9]//g' 输出如下所示:

text-text-text .7.1-text
text-text-text-text .2.4-text
text-text .2.4-text

我该如何解决这个问题?

最佳答案

因为您只想一个应用规则,所以不要使用最后的/g。要仅在后面有数字时应用替换,您应该将其包含在匹配规则中:

sed 's/-\([0-9]\)/ \1/'

由于您不希望替换实际数字,因此上述表达式将其捕获到组 \(...\) 中并通过 \1表达式。

关于linux - 使用 sed,在数字匹配之前只删除一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64571029/

相关文章:

c++ - 为什么我的 C++ 代码在 Linux 上运行而不在 Windows 上运行,RAM 内存有问题吗?

正则表达式查找连续的单词

shell - 从路径中获取文件名

awk - 什么是 NR 和 FNR, "NR==FNR"意味着什么?

regex - 在源代码中的函数调用中间删除换行符

linux - 如何遍历给定目录的所有子目录?

linux - 有没有办法可以将挂载点文件从 Windows 主机绑定(bind)到 linux 容器?

linux - 如何在 bash 中以特定字符串作为排序键对文件进行排序?

linux - 为什么百分号 (%) 在 crontab 中不起作用?

c++ - Linux C++ : cannot run "nmcli dev list iface" when not logged in