(SED) : code works ok via terminal, but not in a bash script. what should i "escape"?

498 views Asked by At

In terminal let's run..

a=' aa a '
b=`echo $a | sed -e 's/^ *//g' -e 's/ *$//g'`

i believe it removes empty spaces from beginning and ending of the script.
but preserves the empty space inbetween

aa a

but when i run this in a bash script.. it returns with

aaa

the empty space in-between string is removed too.

perhaps i need to escape something ?

2

There are 2 answers

0
Bertrand On

Try this :

a="   space a a   " 
b=$(echo $a | sed -e 's/^\ *|\ *$//g') 
echo "<$b>"

it will output :

<space a a>
0
Gordon Davisson On

I'm not sure what's causing the final problem, but there's an earlier problem: referring to variables without double-quotes around them will cause unwanted parsing of the variable's value. For instance, the command echo $a will substitute the value of $a, then perform word splitting (which removes leasing and trailing whitespace, and converts whitespace within the variable into word breaks), then glob (aka wildcard) expansion if any of the words contain wildcards. (And then echo pastes the "words" it receives back together with a single space between them.) echo "$a", on the other hand, echoes the value of $a intact:

$ a='    a    *    aa    '   # Note multuple spaces and a wildcard
$ echo $a "end"    # "end" is there so you can tell if the trailing spaces are echoed
a file1.txt file2.txt file3.pdf aa end
$ echo "$a" "end"
    a    *    aa     end

As a result of this, in b=$(echo $a | sed -e 's/^\ *|\ *$//g') the leading and trailing spaces in $a are removed before the string even gets to sed. This would be fine if that were the only thing that'd been done, but as you saw above the string has been messed with in other (undesirable) ways as well.

As far as I can see, the sed command will do exactly what it should, as long as you pass it the unmangled value of $a:

$ b=$(echo "$a" | sed -e 's/^ *//g' -e 's/ *$//g')
$ echo "$b" "end"    # Note that echo will put a single space between $b and "end"
a    *    aa end
$ echo "'$b'"    # Here's a more direct way to mark the beginning and end of the string
'a    *    aa'

... so it looks to me that something else (probably after the quoted code) is messing with the value of '$b'. Possibly it's being also used without the benefit of double-quotes, and that's causing trouble.