Thursday 29 November 2012

Using $PWD in sed command

>I needed to get the path of my current directory into a file in particular >location, so I tried the conventional method of sed. I used the following code, >where I passed the value of $PWD in variable named path, then I echoed a >string with value of variable path, then I tried to replace GLOBALLY the "path" >with the value of varaible path in the file named a.txt.




path=$PWD
echo "my name is demon and I live in $path"

sed -i "s/path/"$path"/g" a.txt

>I would get the following error

my name is demon and I live in /home/demon/Documents/work/comm
sed: -e expression #1, char 9: unknown option to `s'

>So the solution to this problem is very much simple, just replace the delimiter .with a hash, pipe, colon. and the problem is solved

>example:

path=$PWD
echo "my name is demon and I live in $path"
sed -i "s#path#"$path"#g" a.txt




path=$PWD
echo "my name is demon and I live in $path"
sed -i "s:path:"$path":g" a.txt


path=$PWD
echo "my name is demon and I live in $path"
sed -i "s|path|"$path"|g" a.txt


Works well for me.

No comments:

Post a Comment