1

I want to remove a line in a file containing a path. The path which should be removed is stored in a variable in a bash script.

Somewhere I read that filenames are allowed to contain any characters except "/" and "\0" on *nix systems. Since I can't use "/" for this purpose (I have paths) I wanted to use the nul character.

What I tried:

#!/bin/bash

var_that_contains_path="/path/to/file.ext"

sed "\\\0$var_that_contains_path"\\0d file.txt > file1.txt #not working
sed "\\0$var_that_contains_path"\0d file.txt > file1.txt #not working

How can I make this work? Thanks in advance!

KO70
  • 189
  • 2
  • 15

2 Answers2

1

I think you may be using the wrong tool for the job here. Just use grep:

$ cat file
blah /path/to/file.ext more
some other text
$ var='/path/to/file.ext'
$ grep -vF "$var" file
some other text

As you can see, the line containing the path in the variable is not present in the output.

The -v switch means that grep does an inverse match, so that only lines that don't match the pattern are printed. The -F switch means that grep searches for fixed strings, rather than regular expressions.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
0

Since the filename can contain at least a dozen different characters which have special meaning for sed (., ^, [, just to name a few), the right way to do this is to escape them all in the search string:

Escape a string for a sed replace pattern

So for the search pattern (in this case: the path), you need the following expression:

the_path=$(sed -e 's/[]\/$*.^|[]/\\&/g' <<< "$the_path")
Community
  • 1
  • 1
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176