简体   繁体   中英

sed command to replace multiple spaces into single spaces

I tried to replace multiple spaces in a file to single space using sed.

But it splits each and every character like below. Please let me know what the problem is ...

$ 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 

Your sed command does the wrong thing because it's matching on "zero or more spaces" which of course happens between each pair of characters! Instead of s/ */ /g you want s/ */ /g or s/ +/ /g .

Using tr , the -s option will squeeze consecutive chars to a single one:

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

To downcase as well: tr -s '[:space:]' < test.txt | tr '[:upper:]' '[:lower:]' tr -s '[:space:]' < test.txt | tr '[:upper:]' '[:lower:]'

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

or

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

Good grief that was terse, because * matches zero or more it inserted a space after every character, you want + which matches one or more. Also I switched the order because in doing so you don't have to cat the file.

You can use awk to solve this:

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

Maybe you can match the following regex for multiple spaces:

'\\s+'

and replace with just one space as follows:

' '

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM