用一个空格替换句子结尾后所有出现的两个空格

Zeu*_*eus 9 sed text-processing

我一直在用 sed 命令包含正则表达式。

问:我想用一个空格替换句子结尾后所有出现的两个空格。

这是我所做的:

sed 's/^ $/^$/' file  
Run Code Online (Sandbox Code Playgroud)

并且它没有在句子结束后用一个空格替换两个空格。

我得到的输出:

This is the output.  Hello Hello
Run Code Online (Sandbox Code Playgroud)

我想要的输出:

This is the output. Hello Hello
Run Code Online (Sandbox Code Playgroud)

cuo*_*glm 13

你的sed命令's/^ $/^$/'不会做你想做的。它只是用一行 contains 替换所有包含一个空格的行^$

取决于什么字符标记句子结束,你可以这样做:

sed -e 's/\([.?!]\) \{2,\}/\1 /g' <file
Run Code Online (Sandbox Code Playgroud)

这将在 之后替换 2 个或更多空格.?或者!仅替换一个空格。


Jas*_*sen 12

 sed 's/\.   */. /g' < file
Run Code Online (Sandbox Code Playgroud)

将 dot 后跟两个或多个空格替换为 dot 后跟一个空格。


Rah*_*hul 7

这就是你可能正在寻找的,

tr -s " " <filename
Run Code Online (Sandbox Code Playgroud)

样本,

$ echo "This is the output.  Hello Hello" | tr -s "[:blank:]"
This is the output. Hello Hello
Run Code Online (Sandbox Code Playgroud)

使用sed,

$ echo "This is the output.  Hello Hello" | sed 's/\. \+/. /g'
$ echo "This is the output.  Hello Hello" | sed 's/\. \{1,\}/. /g'
This is the output. Hello Hello
Run Code Online (Sandbox Code Playgroud)

  • 这种方法也将替换不是句子结尾的两个空格。 (3认同)
  • 嗯,它正在工作,谢谢,但我需要包含 sed 命令。请告诉类似上面显示的内容,例如在 sed 中替换、更改文本等。 (2认同)
  • 我不知道这个 tr 功能, (2认同)