Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell Script: How to trim spaces from a bash variable [duplicate]

Tags:

bash

shell

unix

Possible Duplicate:
How to trim whitespace from bash variable?

I have searched and attempted a number of solutions but nothing seems to work for me...

I have a shell variable which is causing issues due to leading and trailing spaces. how can we get rid of all the spaces in a single line using shell script?

like image 550
Bharat Sinha Avatar asked Aug 03 '12 07:08

Bharat Sinha


2 Answers

I can think of two options:

variable="  gfgergj lkjgrg  "
echo $variable | sed 's,^ *,,; s, *$,,'

or else

nospaces=${variable## } # remove leading spaces
nospaces=${variable%% } # remove trailing spaces
like image 160
jpmuc Avatar answered Nov 04 '22 15:11

jpmuc


there are so many ways to achieve that, awk oneliner:

kent$  echo "    foo  -  -  -  bar   "|awk '{sub(/^ */,"",$0);sub(/ *$/,"",$0)}1'
foo  -  -  -  bar
like image 33
Kent Avatar answered Nov 04 '22 15:11

Kent