LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   SED with variable that contains spaces? (https://www.linuxquestions.org/questions/linux-newbie-8/sed-with-variable-that-contains-spaces-4175424594/)

mp85 08-29-2012 09:25 AM

SED with variable that contains spaces?
 
Im having problems using SED to replace with a variable. I assume the problem is that the variable contains spaces.

Code:

data=$(grep 'DATA' vsm.scr)
echo $data
sed "s/loc/$data/g" v1.scr > v2.scr

I just did the echo to make sure my variable is correct which it is. It has the format below:

DATA /home/temp/abc.txt


(There are additional spaces in front of DATA, they dont show up in the forum post)

Ive tried setting the variable as a simple number and everyhting works fine, which leads me to believe its a problem with the spaces

Any ideas?

grail 08-29-2012 09:49 AM

Please provide an example of the line being replaced? As it stands i am unable to reproduce a problem.

mp85 08-29-2012 10:02 AM

sed "s/loc/$data/g" v1.scr > v2.scr


loc is being replaced and is not a variable.
$data has the following format:
Code:

          DATA /home/temp/abc.txt
Note: there are ~10 spaces in the front (also $data is only one line its just showing up with an extra blank line after from the forum post)

colucix 08-29-2012 11:18 AM

The problematic characters are not the spaces, since you correctly used double quotes to embed the sed command, but the slashes. They interfere with the separator used in the s command. To avoid this unwanted behaviour, use another character as separator, e.g.
Code:

sed "s:loc:$data:g" v1.scr > v2.scr
The general rule is that any character used immediately after the s command is treated as separator. You have only to choose a character that doesn't appear in any of the strings (a colon or a "@" are often a good choice).

mp85 08-29-2012 11:25 AM

Quote:

Originally Posted by colucix (Post 4767502)
The problematic characters are not the spaces, since you correctly used double quotes to embed the sed command, but the slashes. They interfere with the separator used in the s command. To avoid this unwanted behaviour, use another character as separator, e.g.
Code:

sed "s:loc:$data:g" v1.scr > v2.scr
The general rule is that any character used immediately after the s command is treated as separator. You have only to choose a character that doesn't appear in any of the strings (a colon or a "@" are often a good choice).

Thanks so much. Worked perfectly!


All times are GMT -5. The time now is 10:25 PM.