regexlinuxstringsed

Delete lines in file if they contain current working directory


This basically boils down to "How do I combine pwd and sed delete (or alternative)". Given a file with a list of file paths, how do I delete lines which contain my current directory?

So, if file1 contains:

/dirA/subdir1/somefile
/dirB/subdir2/somefile
/dirB/subdir2/somefile
/dirC/subdir2/somefile
/dirD/subdir1/somefile

And my working directory is:

/dirB/subdir2/

Then my output should edit file1 in place to result in:

/dirA/subdir1/somefile
/dirC/subdir2/somefile
/dirD/subdir1/somefile

I know that I can delete lines with:

sed '/pattern to match/d' file1

And I can feed pwd into sed like so:

sed 's?#REPLACE-WITH-PATH?'`pwd`'?'

So I thought I could combine them as one of the following:

sed '/'`pwd`'/d' file1
sed '?'`pwd`'?d' file1
sed '#'`pwd`'#d' file1

The first option won't read properly, because it interprets the slashes of the path as part of the sed command. The second doesn't recognize the question mark. The third runs, but doesn't do anything.


Solution

  • Because your current directory contains / I suggest to switch from /.../d to \|...|d or \#...#d .