【问题标题】:sed command to replace multiple spaces into single spacessed 命令将多个空格替换为单个空格
【发布时间】:2014-05-21 06:49:15
【问题描述】:

我尝试使用 sed 将文件中的多个空格替换为单个空格。

但它会像下面那样拆分每个字符。 请告诉我问题是什么...

$ cat test.txt
 iiHi Hello   Hi
this   is   loga

$

$ cat test.txt | tr [A-Z] [a-z]|sed -e "s/ */ /g"
 i i h i h e l l o h i
 t h i s i s l o g a 

【问题讨论】:

标签: regex shell sed


【解决方案1】:

您的sed 命令做错了,因为它匹配“零个或多个空格”,这当然发生在每对字符之间!而不是s/ */ /g 你想要s/ */ /gs/ +/ /g

【讨论】:

  • 为了澄清,空间必须被转义,所以它是:s/\ \ */\ /gs/\ +/\ /g
  • 仅当 sed 的参数没有被引号包围时
【解决方案2】:

使用tr-s 选项会将连续的字符压缩为一个:

tr -s '[:space:]' < test.txt
 iiHi Hello Hi
this is loga

也要小写:tr -s '[:space:]' &lt; test.txt | tr '[:upper:]' '[:lower:]'

【讨论】:

  • 这应该得到更多的支持!从未听说过这个实用程序。
【解决方案3】:
sed 's/ \+/ /g' test.txt | tr [A-Z] [a-z]

sed 's/\s\+/ /g' test.txt | tr [A-Z] [a-z]

很遗憾,这很简洁,因为* 匹配零个或多个它在每个字符后插入一个空格,你想要匹配一个或多个的+。我也切换了顺序,因为这样做你不必cat 文件。

【讨论】:

  • sed 必须带有 '-r',否则正则表达式将不起作用sed -r 's/\s\+/ /g' test.txt
  • @Temak - 这必须取决于 sed 的风格,使用 GNU sed 4.4 我不需要标志。
【解决方案4】:

你可以使用awk来解决这个问题:

awk '{$0=tolower($0);$1=$1}1' test.txt
iihi hello hi
this is loga

【讨论】:

    【解决方案5】:

    也许您可以为多个空格匹配以下正则表达式:

    '\s+'

    并用一个空格替换如下:

    ' '

    【讨论】:

    • 这需要-E-flag 来扩展正则表达式。
    猜你喜欢
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 2014-06-22
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多