Reputation: 8366
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
Upvotes: 23
Views: 55467
Reputation: 839
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.
Upvotes: 13
Reputation: 41460
You can use awk
to solve this:
awk '{$0=tolower($0);$1=$1}1' test.txt
iihi hello hi
this is loga
Upvotes: 3
Reputation: 247210
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:]'
Upvotes: 32
Reputation: 249642
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
.
Upvotes: 29
Reputation: 32197
Maybe you can match the following regex for multiple spaces:
'\s+'
and replace with just one space as follows:
' '
Upvotes: 0