-2

I have a file that contains names of directories and some other information, but the names always come first.The file looks like this:

/home/user/Desktop/IS/proj_1/sch/text 4 2018-03-14 07:41:01
/home/user/Desktop/IS/file1.txt 3 2018-03-14 16:50:01
...

I have a variable "name" that contains this for example:

/home/user/Desktop/IS/file1.txt

And I need to delete that one particular line from the file somehow. I've searched many posts and tried using various quotations and ways of expansions, but nothing did the trick. If I type it in directly, it deletes the line without problem, but I'm having a hard time doing it from a variable. This is what I came up with but it still doesn't work.

sed -i '/"$name"/d' $File_name
sak
  • 1,230
  • 18
  • 37
Saeko
  • 421
  • 1
  • 4
  • 14

3 Answers3

1

sed command doesn't allow plain string based search and performs search using only a regex (BRE or ERE). That requires escaping all special regex meta-characters in search pattern.

Better to use a non-regex approach using awk:

name='/home/user/Desktop/IS/file1.txt'
awk -v p="$name" '!index($0, p)' file

/home/user/Desktop/IS/proj_1/sch/text 4 2018-03-14 07:41:01
anubhava
  • 761,203
  • 64
  • 569
  • 643
1

Try this :

sed -i "\|$name|d" "$File_name"

As you can see, I changed the delimiter for |, you can pick another one depending of your needs from most of ascii characters (not all works)

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
1

Whatever given in single quotes wont get expanded.

Try:

sed -i "/$name/d" $File_name

If you have problems with /, escape them properly.

name=$(echo "$name"|sed -e "s/\//\\\\\//g")
sed -i "/$name/d" $File_name
Axeon Thra
  • 334
  • 3
  • 14