![将句子末尾出现的所有两个空格替换为仅一个空格](https://linux22.com/image/91001/%E5%B0%86%E5%8F%A5%E5%AD%90%E6%9C%AB%E5%B0%BE%E5%87%BA%E7%8E%B0%E7%9A%84%E6%89%80%E6%9C%89%E4%B8%A4%E4%B8%AA%E7%A9%BA%E6%A0%BC%E6%9B%BF%E6%8D%A2%E4%B8%BA%E4%BB%85%E4%B8%80%E4%B8%AA%E7%A9%BA%E6%A0%BC.png)
我陷入了用 sed 命令包含正则表达式的困境。
问:我想替换后面出现的所有两个空格句子的结尾只有一次空间。
这是我所做的:
sed 's/^ $/^$/' file
并且在句子结束后它并没有用一个空格替换两个空格。
我得到的输出:
This is the output. Hello Hello
我想要的输出:
This is the output. Hello Hello
答案1
你的sed
命令's/^ $/^$/'
不会做你想做的事。它只是将所有包含一个空格的行替换为包含一行^$
。
根据标记句子结尾的字符,您可以执行以下操作:
sed -e 's/\([.?!]\) \{2,\}/\1 /g' <file
这将替换 后的 2 个或多个空格.
,?
或!
仅替换 1 个空格。
答案2
sed 's/\. */. /g' < file
将点后跟两个或多个空格替换为点后跟一个空格。
答案3
这可能就是您正在寻找的,
tr -s " " <filename
样本,
$ echo "This is the output. Hello Hello" | tr -s "[:blank:]"
This is the output. Hello Hello
使用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