LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   replace path (https://www.linuxquestions.org/questions/linux-newbie-8/replace-path-4175433736/)

mmhs 10-23-2012 04:15 PM

replace path
 
hi guys
i have a simple question

i have some variables they contain path addresses i want to replace old address with new address

e.g

echo $m=/tmp/files3/New/test

i want to replace /tmp/files3 with /root/new

i used sed but it didnt work

echo $m | sed "s-/tmp/files3-/root/new"

what ca i do ???

jack_ 10-23-2012 04:53 PM

export m='/tmp/files3'

sycamorex 10-23-2012 04:55 PM

Where do you want to replace them? In a script, your environment just for this session, in your environment permanently? Where are the original values stored?

mmhs 10-23-2012 05:00 PM

Quote:

Originally Posted by jack_ (Post 4813384)
export m='/tmp/files3'

what's this ???
???????????!!!!!!!!

sycamorex 10-23-2012 05:10 PM

Quote:

Originally Posted by mmhs (Post 4813389)
???????????!!!!!!!!

What is that?:)

jack_ 10-23-2012 05:13 PM

Quote:

Originally Posted by mmhs (Post 4813389)
what's this ???
???????????!!!!!!!!

whoop my bad, i don't know what i was thinking.

here:

echo $m | sed 's/tmp\/files3/root\/new/'

sycamorex 10-23-2012 05:18 PM

Quote:

Originally Posted by jack_ (Post 4813397)
whoop my bad, i don't know what i was thinking.

here:

echo $m | sed 's/tmp\/files3/root\/new/'

Well, if anything, it'll be:

Code:

echo $m | sed 's/\/tmp\/files/\/root\/new/'
but without knowing the context, I still fail to see the point of doing all of that.

David the H. 10-25-2012 12:48 PM

There's no need for sed. Once a value is in a variable, you really only need built-in parameter substitution.

Code:

m=/tmp/files3/New/test
a=/tmp/files3
b=/root/new

echo "${m/$a/$b}"

echo "$b${m#$a}"

The second one is a more portable version (the "${var/match/replace}" pattern is only available in bash and some other modern shells), but it assumes that the string to replace is at the front of the variable.


Bash also has many more string manipulation options available, and you should generally rely on them for simple operations like this. Save the external tools like sed and awk for operating on text files and other large blocks of text that need to be processed en masse.


All times are GMT -5. The time now is 09:33 AM.