System Administration
cancel
Showing results for 
Search instead for 
Did you mean: 

how to remove leading and trailing spaces from string?

 
SOLVED
Go to solution
diwakar_4
Frequent Advisor

how to remove leading and trailing spaces from string?

ho All,

I have to remove heading and trailing spaces from string.

Name=" Mark Barnatsom "

I want out put as:
Mark Barnatson.

Can some one help me to do this?

Thanks
9 REPLIES
Mel Burslan
Honored Contributor

Re: how to remove leading and trailing spaces from string?

Name=" Mark Barnatsom "
TrimmedName=`echo ${Name}|sed -e "1,1s/^ //" | sed -e "1,1s/ $//"`

To show the effects

echo "##"${Name}"##"; echo "##"${TrimmedName}"##"

I am sure there is a craftier solution using PERL or awk, but this is what I could come up with at the moment.

Hope this helps
________________________________
UNIX because I majored in cryptology...
James R. Ferguson
Acclaimed Contributor

Re: how to remove leading and trailing spaces from string?

Hi :

Another way is with Perl. This will handle spaces and/or tab characters:

# echo ${Name}|perl -ple 's/^\s*//;s/\s*$//'

Regards!

...JRF...
Steven Schweda
Honored Contributor

Re: how to remove leading and trailing spaces from string?

You don't need two pipes and two sed's:

bash$ x=` echo ' a b c ' | sed -e 's/^ *//' -e 's/ *$//' `
bash$ echo ">$x<"
>a b c<
Ganesan R
Honored Contributor

Re: how to remove leading and trailing spaces from string?

Hi,

#echo "string" |cut -c

Examble:

# echo "Name=" Mark Barnatsom "" |cut -c 7-21
Mark Barnatsom
#
Best wishes,

Ganesh.
Tingli
Esteemed Contributor

Re: how to remove leading and trailing spaces from string?

NAME=${NAME%% }
NAME=${NAME## }
Tingli
Esteemed Contributor
Solution

Re: how to remove leading and trailing spaces from string?

Another easy way.

NAME=$(echo $NAME)
Steven Schweda
Honored Contributor

Re: how to remove leading and trailing spaces from string?

> Another easy way.
> [...]

Easy, but it doesn't do what was requested
("remove leading and trailing spaces").

bash$ x=` echo ' a b c ' | sed -e 's/^ *//' -e 's/ *$//' `
bash$ echo ">$x<"
>a b c<

bash$ NAME=' a b c '
bash$ echo ">$(echo $NAME)<"
>a b c<

Now, if you _want_ to reduce the interior
white space to single spaces, that's fine,
but it's not what was requested.
diwakar_4
Frequent Advisor

Re: how to remove leading and trailing spaces from string?

Thanks to all,

All are correct but i used Tinqli second answer and James answer.

Thank you very much for giving your valuable time.

Thanks
Suraj K Sankari
Honored Contributor

Re: how to remove leading and trailing spaces from string?

Hi,
If your field saperator is " then you can use this also

awk -F"\"" '{ print $1 }'
Suraj