如果使用带有扩展语法的 sed 和正则表达式的特定模式的一部分,则用新行替换空格

Replace spaces with new lines if part of a specific pattern using sed and regex with extended syntax

所以我有一个包含多个实例的文本文件,如下所示:

word. word or words [something:'else]

我需要用一个新行替换双 space,在每个句点后跟一个单词序列,然后是一个“[”,如下所示:

word.\nword or words [something:'else]

我考虑过在 bash 中使用带有扩展正则表达式语法的 sed 命令,但到目前为止没有任何效果......我尝试了不同的变体:

sed -E 's/(\.)( )(.*)(.\[)/\n/g' old.txt > new.txt

我是这方面的绝对初学者,所以我完全不确定自己在做什么

您的 sed 命令几乎正确(但包含一些冗余)

sed -E 's/(\.)(  )(.*)(.\[)/\n/' old.txt > new.txt
#                                   ^
#                                   You forget terminating the s command

但您不需要捕获所有内容。一个更简单的可以是

sed -E 's/\.  (.*\[)/.\n/' old.txt > new.txt

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

sed -E 's/\.  ((\w+ )+\[)/\.\n/g' file

全局替换句点后跟两个 space 和一个或多个单词 space 分隔,后跟左方括号;一个句点后跟一个换行符,然后是来自正则表达式的匹配反向引用。