LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   variables within sed substitutions? (https://www.linuxquestions.org/questions/programming-9/variables-within-sed-substitutions-573148/)

ocicat 07-29-2007 08:57 AM

variables within sed substitutions?
 
Hi, I have yet another sed question. The following script unsuccessfully attempts to expand tildes within pathnames:
Code:

#!/bin/sh

expand()
{
    dir=`echo $1 | sed 's/^~/$HOME/'`
    echo $dir
}

expand '~'
expand '~/bin'

...with the output being:
Code:

$HOME
$HOME/bin

Whereas, the intended result is:
Code:

/home/username
/home/username/bin

How can the sed string substitution be corrected?

Thank you.

pixellany 07-29-2007 10:11 AM

See those single quotes?---To bash, they say: "don't attempt to interpret any special characters here--just pass them on to sed."

"$" has a different meaning to sed.

By using double-quotes, the "$" will be read by bash. (Then, to get back the sed meaning, you would need to use "\$")

So, the corrected line is:
dir=`echo $1 | sed "s/^~/$HOME/"`

Bash Guide for Beginners--by Machtelt Garrels....free at tldp.org
Also there: Advanced bash scripting guide by Mendel Cooper

colucix 07-29-2007 10:20 AM

Why don't simply let the bash to expand by itself (without using single quotes, as pixellany pointed out)?
Code:

#!/bin/bash
dir=`echo ~/bin`  # or simply: dir=~/bin
echo $dir

gives
Code:

/home/colucix/bin

ocicat 07-29-2007 12:17 PM

Quote:

Originally Posted by colucix
Why don't simply let the bash to expand by itself (without using single quotes, as pixellany pointed out)?

I'm using the Bourne shell, not Bash. pixellany is correct though about using double quotes instead of single (which I missed...). With double quotes string contents go through interpolation, meaning that the value of variables are substituted. This doesn't occur with single quotes. I'm guessing this has been part of shell programming from the beginning. Perl does the same thing, as it follows a lot of shell behavior given that originally Perl was meant to be an embellishment upon older shell themes.

Thanks to both for your answers.


All times are GMT -5. The time now is 02:12 AM.