1
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

ypp
  • 141
  • 10

3 Answers3

2

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.

Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • You can also use different delimiters for sed. – 123 Apr 19 '16 at 12:41
  • @123 I tried and I do use them for the `sed 's/XXX/YYY/g` syntax, but I couldn't for the `sed /ZZZ/d`. – fedorqui Apr 19 '16 at 12:42
  • 2
    You need to escape the first delimiter if it is not a substitution. i.e `sed "\:$string:d"` – 123 Apr 19 '16 at 12:44
  • 1
    @123 oh, great discovery! I wasn't aware of that (do you have any source?). Many thanks, updated – fedorqui Apr 19 '16 at 12:47
  • 1
    It's in the man page in the addresses section. `\cregexpc >> Match lines matching the regular expression regexp. The c may be any character` – 123 Apr 19 '16 at 12:49
  • 1
    @fedorqui My directory has the _ in name so I used @ instead. `sed "\@${PWD}@d" file.txt`. It worked great thanks. – ypp Apr 19 '16 at 13:02
1

grep can also do the job:

grep -v "$(pwd)" file
oliv
  • 12,690
  • 25
  • 45
0

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
Community
  • 1
  • 1
Paul Zakharov
  • 515
  • 2
  • 15