LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   replace string with empty string of dir path (https://www.linuxquestions.org/questions/linux-newbie-8/replace-string-with-empty-string-of-dir-path-872549/)

ted_chou12 04-02-2011 05:31 AM

replace string with empty string of dir path
 
Hi, I want to replace a string of directory path in a string to empty:
Code:

dd="test"
STRING="/mnt/sda1/record/$dd/"
j=$(echo "/mnt/sda1/record/test/somefile.test"|sed 's/$STRING//g')

But this doesnt seem to give me the desired thing:
Code:

j=$(echo "/mnt/sda1/record/test/somefile.test"|sed 's/\/mnt\/sda1\/record\/test\///g')
this gives the desired outcome, but its specific, i need a variable in the sed not a string. And if I replace STRING="\/mnt\/sda1\/record\/$dd\/" then I cant use it for something else, cause its has all the weird backslashes now.
Thanks

colucix 04-02-2011 05:38 AM

If the pattern is a variable you have to let the shell substitute it by changing single quotes with double quotes, otherwise the word $STRING is interpreted literally. If the pattern contains slashes, you might use another character as separator in the s command, e.g.
Code:

... | sed "s:$STRING::g"
Also check the basename command, since from your example it provides the required functionality.

grail 04-02-2011 06:37 AM

Or you could store the path and use parameter substitution:
Code:

dd="test"
STRING="/mnt/sda1/record/$dd/"
path="/mnt/sda1/record/test/somefile.test"

j=${path#$STRING}


ted_chou12 04-02-2011 06:43 AM

thanks!


All times are GMT -5. The time now is 10:46 AM.