Problem passing a specific variable to sed

Hi, I'm a bit of sed n00b here.

My issue is as follows:

I'm trying to pass a variable to sed so that all instances of this variable (in a text file) will be replaced with nothing. However, the value of this variable will always be a folder location e.g. "C:\Program Files\Folder1"

I currently have

sed "s/$VAR1//g" file.txt > file_processed.txt

Unfortunately this isn't working. I have also tried

sed s/$VAR1//g file.txt > file_processed.txt
sed 's/'$VAR1'//g file.txt > file_processed.txt

I am also using Korn Shell.

Please be gentle with your responses puts on flame-proof jacket :wink:

Try :

sed 's!'$VAR1'!!g' filename >file_processed

By "not working" I assume you mean the substitution doesn't come out the way you like it, because the backslashes are interpreted by sed, not used as literal characters in the substitution.

To solve that, you basically have to double every backslash in the substitution string before giving it to sed.

echo "$VAR" | sed -e 's/\\/\\\\/g' -e 's/.*/s%&%%g/' | sed -f - file.txt >file_processed

If your sed doesn't like getting a dash (standard input) as the argument to the -f option, some further workarounds are needed. Maybe you could simply use Perl instead /-:

perl -pe 'BEGIN { $v = quotemeta(shift); }
  s/$v//go' 'C:\Program Files\Folder1' file.txt >file_processed

Gave that a try but didn't work. Thanks for the help though.

Tried

echo "$VAR" | sed -e 's/\\/\\\\/g' -e 's/.*/s%&%%g/' | sed -f - file.txt >file_processed

but got the error

sed: newline or end of file found in pattern

The sed script works here, not sure how to fix it. Can you identify which part gives the error? (Try remove parts of the script starting from the end, until you no longer get the error message.) I'm guessing you might need to tweak the number of backslashes in s/\\/\\\\/g but that's a cheap shot.

I exited shell, and started it again and got it to work, not entirely sure why it didn't work before, but it does now!

Thanks for the assistance, it does exactly what I want it to now. :b: