24

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 
1

5 Answers 5

34

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:]'

Sign up to request clarification or add additional context in comments.

1 Comment

This should have been more upvoted! Never heard of this utility.
29

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.

2 Comments

just for clarify, space must be scaped, so it is: s/\ \ */\ /g or s/\ +/\ /g
Only if the argument to sed isn't surrounded by quotes
14
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.

3 Comments

sed must be with '-r', otherwise regexps would not work sed -r 's/\s\+/ /g' test.txt
@Temak - that must be dependent on the flavor of sed, with GNU sed 4.4 I did not need the flag.
$ man sed | grep s\/reg -A1 s/regexp/replacement/ Attempt to match regexp against the pattern space. If successful, replace that portion matched with replacement. The replacement may contain the special character & to
4

You can use awk to solve this:

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

Comments

0

Maybe you can match the following regex for multiple spaces:

'\s+'

and replace with just one space as follows:

' '

1 Comment

This needs the -E-flag for extended regexes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.