From within a bash script, how can I use sed to write to a file where the filename is stored in a bash variable?  Output redirection won't do because I want to edit one file in place, pulling lines that match a regex into a different file and deleting them in the first file.Something like:sed -i '/^my regex here$/{;w file2;d;}' file1...but where file1 and file2 are both actually variables that hold the filenames.  (Such as file2=$(mktemp).)So what I really want is variable expansion for the filename, but no expansion for the rest of the sed command, and leaving the whole thing as a single argument passed to the sed command.For whatever reason, the following does not work:sed -i '/my regex here/{;w '$file2';d;}' $file1It says unmatched { and I can't see why.Any way I can do this?
How to use sed to write to a filename stored in a variable?
sed
Because you're using a single sed expression, everything that follows after the w (including the }) is interpreted as the wfile name: The argument wfile shall terminate the editing command.You can see that if you add a second command } e.g. like:sed -e '/my regex here/{w '$file2';d;}' -e '}' $file1then the lines matching my regex here will be saved in a file named whatever;d;} where whatever is whatever $file1 expands to.The correct syntax is via separate commands, either with several expressions:sed -e '/my regex here/{w '$file1 -e 'd' -e '}' $file2or one command per line:sed '/my regex here/{w '$file1'd}' $file2