Operating System - HP-UX
1752337 Members
5641 Online
108787 Solutions
New Discussion юеВ

remove extra spaces in a string

 
manasa_1
Occasional Contributor

remove extra spaces in a string

Hello,

i want to remove extra spaces in my string in unix. which command i need to use.

Ex: i am rahul. this is the string now i want the result to be as : i am rahul

3 REPLIES 3
Yogeeraj_1
Honored Contributor

Re: remove extra spaces in a string

hi,

it seems that you already have a similar thread at:
http://forums11.itrc.hp.com/service/forums/questionanswer.do?threadId=1210930

please check and let us know if the solutions provided are helpful.

Otherwise, clarify your question further.

kind regards
yogeeraj
No person was ever honoured for what he received. Honour has been the reward for what he gave (clavin coolidge)
Hein van den Heuvel
Honored Contributor

Re: remove extra spaces in a string

manasa,

Where is the string coming from / going to?
Is it in a file? a shell variable? what shell?

What problem are you really trying to solve?
The answer to that question will help define the optimal answer to the part question you asked.

If you choose to explain the problem better be sure to click 'Retain format(spacing). URLs will not be clickable' because as you see, the itrc forum mangled your entrie to loose teh cirtical example. In addition you may want to attach a .txt file with EXACT input examples and EXACT desired output.


Anyway...
If it is in a shell variable then just a simple print will 'clean it up' and we can use that:

$ x='aap noot mies'
$ print "$x"
aap noot mies
$ print $x
aap noot mies
$ y=$(print $x)
$ print "x:$x.y:$y"
x:aap noot mies.y:aap noot mies
$

Or you can feed it to 'sed'
For example:
$ y=$(print "$x" | sed 's/ */*/g')
$ print "$y"
aap*noot*mies

So the RE (regular expression) is to match a space, followed by zero or more spaces.
To be replaced in the example by *, but a space for you.

spaces or white-space (tabs also)?

Good luck,
Hein.
Arturo Galbiati
Esteemed Contributor

Re: remove extra spaces in a string

Hi,
tr -d " "
will remove all spaces in the string.
The use depends where you have your string: var, file, etc.

HTH,
Art