First of all, please use
[code][/code] tags around your code and data, to preserve formatting and to improve readability. Please do not use quote tags, colors, or other fancy formatting.
Code:
sed -e /"$string"/d $text > "$text"
This is unclear to me.
sed operates on
files when this syntax is used. So does the
$text variable hold the name of a file that contains the text, or the actual text itself? If the former, then you cannot use the same file for both input and output. You usually end up with an empty file, as the "
>" redirection is processed first, overwriting the contents before the rest of the command is run. You have to work through a temporary file.
gnu sed does have a
-i option for writing in place, though.
If the variable is intended to contain the text itself, as your description appears to state, then not only can you not use this syntax (you have to feed the contents into sed's stdin in some way), but you also can't use "
>" to redirect stdout into a variable. The variable contents will be treated as a filename to use. You have to use some kind of command substitution, or
read, or a similar technique, to store the stdout of a command inside a variable.
Finally, you also need to enclose the entire sed expression in double-quotes, so that it's passed to it as a single argument.
Catkin's example shows you how it's done.
By the way, when modifying the contents of a variable, you can often use simple built-in
parameter substitution instead of external tools.
Code:
$ text='line one
+ line two
+ line three'
$ echo "$text"
line one
line two
line three
$ string='line two' #the line to be removed
$ echo "${text/$string}" #removes the text, but not the newline character
line one
line three
$ echo "${text/$string$'\n'}" #also remove the newline
line one
line three
Notice how you can use ansi-c style quoting (
$'', see the quoting section of the bash man page) to generate a newline. You may need to enable
shopt -s extquote first if you use it in a non-interactive script, or else include the newline directly in the
string variable.
Code:
$ string=$'line two\n'
$ echo "${text/$string}"
line one
line three
Finally, I also want to mention that, depending on the content (e.g. if the variable contains a list of filenames), it might possibly be better to use an array instead, with one line per entry, rather than a single variable with multiple lines.
http://mywiki.wooledge.org/BashFAQ/005