ypp ypp - 7 months ago 13
Bash Question

Delete lines from input file after exact matching the prefix path till $(pwd) in the file

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

Answer

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.