File.txt
/aaa/bbb/ccc/ddd
/aaa/bbb/ccc/mmm
/aaa/eee/ccc/ddd
if my $(pwd)
is /aaa/bbb/ccc
the it should delete only first two
I have tried like sed /^$(pwd)/d
but not worked
The problem here is that you are using $(pwd)
, which tries to execute a command pwd
. This result contains slashes, so that the final command is something like:
sed /^/aaa/bbb/ccc/d
Which sed
cannot handle and returns an error:
sed: -e expression #1, char 4: extra characters after command
You should instead use another delimiter. For example, _
:
sed "\_${PWD}_d"
As 123 comments below, you need to escape the first delimiter if it is not a substitution. I also enclose the var within ${ }
to prevent the variable to be considered PWD_
instead of PWD
.
You can use awk
for a nicer approach:
$ awk -v patt="$PWD" '!($0 ~ patt)' file
/aaa/eee/ccc/ddd
Note $PWD
is the same as executing pwd
.
Just to precise the answer of fedorqui...
In your question there is another problem because you variable $pwd contain special sed symbols (/). So the sed will not be glad...
Some solution for example could be find here : Replace a string in shell script using a variable
So you could use additional variable to correct this problem.
This work perfectly for your example (I just replace echo $(pwd) by 'echo /aaa/bbb/ccc').
pwd_bis=$( echo $(pwd) | sed 's/[\/]/\\\0/g' )
sed "/^${pwd_bis}/d" File.txt