[Sussex] Bash string substitution

Ronan Chilvers ronan at thelittledot.com
Fri Sep 30 13:32:34 UTC 2005


On Fri, 30 Sep 2005 14:20:46 +0100
Steve Dobson <steve at dobson.org> wrote:

> Ronan
> 
> On Fri, Sep 30, 2005 at 01:55:44PM +0100, Ronan Chilvers wrote:
> > Sorry to reply to my own post but just cracked it:
> > 
> > for FIL in "Catalogue labels Size "$1/.*; do
> > 	PAT="s/A/BC/g"
> > 	NEW=$(basename "$FIL" | sed "$PAT")
> > 	echo $NEW
> > done
> > 
> > I was using single rather than double quotes on my sed expression
> > which is where the problem lay...
> 
> I always use signle quotes on my sed scripts.  I would have writen
> your line as:
>    $NEW=`basename $FIL | sed -e 's/A/BC/g'`

That's what I had originally.  However I was using it in a script with
a range of substitutions so the A and BC needed to be variables like:-

$NEW=`basename $FIL | sed -e 's/$1/$2/g'`

where $1 was always a single character, but $2 varied between 1 and 2
characters.  The problem I had was that the single quotes didn't allow
variable substitution to happen so the $1 and $2 where taken as
literals which didna' work, cap'n!!  Didn't realise single /
double quotes meant different things in bash too (as it does in other
languages).

Cheers

Ronan
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mailman.lug.org.uk/pipermail/sussex/attachments/20050930/ef0f312b/attachment.pgp 


More information about the Sussex mailing list