如何使用Bash用单个空格替换多个空格? [英] How to replace multiple spaces with a single space using Bash?

查看:108
本文介绍了如何使用Bash用单个空格替换多个空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用bash将一个字符串中的多个相邻空格替换为一个空格.示例:

I'd like to use bash to replace multiple adjacent spaces in a string by a single space. Example:

原始字符串:

"too         many       spaces."

已转换的字符串:

"too many spaces."

我已经尝试过"${str//*( )/.}"awk '{gsub(/[:blank:]/," ")}1'之类的东西,但我做对了.

I've tried things like "${str//*( )/.}" or awk '{gsub(/[:blank:]/," ")}1' but I can't get it right.

注意:我能够使其与<CMD_THAT_GENERATES_THE_INPUT_STRINGH> | perl -lpe's/\s+/ /g'一起使用,但是我不得不使用perl来完成这项工作.如果可能的话,我想使用一些bash内部语法,而不是调用外部程序.

Note: I was able to make it work with <CMD_THAT_GENERATES_THE_INPUT_STRINGH> | perl -lpe's/\s+/ /g' but I had to use perl to do the job. I'd like to use some bash internal syntax instead of calling an external program, if that is possible.

推荐答案

使用tr:

$ echo "too         many       spaces." | tr -s ' '
too many spaces

man tr:

-s, --squeeze-repeats
       replace each sequence of a repeated character that is listed  in
       the last specified SET, with a single occurrence of that charac‐
       ter

哦,顺便说一句:

$ s="foo      bar"
$ echo $s
foo bar
$ echo "$s"
foo      bar

编辑2 :关于演出:

$ shopt -s extglob
$ s=$(for i in {1..100} ; do echo -n "word   " ; done) # 100 times: word   word   word...
$ time echo "${s//+([[:blank:]])/ }" > /dev/null

real    0m7.296s
user    0m7.292s
sys     0m0.000s
$ time echo "$s" | tr -s ' ' >/dev/null

real    0m0.002s
user    0m0.000s
sys     0m0.000s

超过7秒?!这怎么可能呢.好吧,这款迷你笔记本电脑来自2014年,但仍然如此.再来一次:

Over 7 seconds?! How is that even possible. Well, this mini laptop is from 2014 but still. Then again:

$ time echo "${s//+( )/ }" > /dev/null

real    0m1.198s
user    0m1.192s
sys     0m0.000s

这篇关于如何使用Bash用单个空格替换多个空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆