Operating System - Linux
1752689 Members
5528 Online
108789 Solutions
New Discussion юеВ

Re: Replace 1 or multiple spaces or tabs with a single space

 
SOLVED
Go to solution
PatRoy
Regular Advisor

Replace 1 or multiple spaces or tabs with a single space

Hi!

First, I'm using standard POSIX Shell. Not Bash.
Additionnally, it's HP's standard sed also. Not GNU Sed.

I'm trying to replace 1 or more spaces/tabs with a single on each occurrence.

In Perl, I think it would be something like this:

s/\s+/ /g

'\s' being recognize has either a space or tab.

I can't make it work with HPUX 11.11 or 11.23 sed. My script is already written in shell, so I was hopping not to go Perl.

Thanks.

Patrick
6 REPLIES 6
James R. Ferguson
Acclaimed Contributor
Solution

Re: Replace 1 or multiple spaces or tabs with a single space

Hi Patrick:

# echo "a b c"|tr -s [[:space:]] " "

Of course, the Forum will probably lose the multiple spaces and tabs in this example!

Regards!

...JRF...
Patrick Wallek
Honored Contributor

Re: Replace 1 or multiple spaces or tabs with a single space

Hi Patrick,

Try using tr instead.

tr -s [:space:] " "

will do what you want. To use tr you can do:

tr -s [:space:] " " < testfile

To get the output to a file:

tr -s [:space:] " " < testfile > testfile.new

you can also do:

cat testfile | tr -s [:space:] " " > testfile2

You have all kinds of options.
spex
Honored Contributor

Re: Replace 1 or multiple spaces or tabs with a single space

Hi,

Give 'tr -s ...' a try:

$ tr -s " \t" " " < filein > fileout

PCS
Peter Nikitka
Honored Contributor

Re: Replace 1 or multiple spaces or tabs with a single space

Hi,

this will do it (it's [spaceTAB]):
sed '/s[ ][ ]*/ /g'

Enter a real tab for .
If you don not want to convert TAB(s) to space (like in your example), but to a single TAB, use - untested -
sed -e 's/ */ /g' -e 's/ ** *//g'

First is 'spacespace*', last is 'space*TABTABspace*'.

mfG Peter
The Universe is a pretty big place, it's bigger than anything anyone has ever dreamed of before. So if it's just us, seems like an awful waste of space, right? Jodie Foster in "Contact"
PatRoy
Regular Advisor

Re: Replace 1 or multiple spaces or tabs with a single space

Thanks James and others!

tr -s [:space:] " " didn't work for me. Had tried it like that, but doesn't do it.

You somehow need 2 set of square brakets: [[:space:]]

That did it.
Thanks again!
James R. Ferguson
Acclaimed Contributor

Re: Replace 1 or multiple spaces or tabs with a single space

Hi (again) Patrick:

Please consider assigning points for the help you have been offered in this and your other threads as listed in your profile.

...JRF...