You may be able to use the LOAD_FILE
function given in the answer to the question that Charles Sprayberry links to above. That would look like this:
mysql -p -u user -e "update my_table set body=load_file('/path/to/filename') where id=x;" dbname
If that doesn't work out for you (e.g., due to permissions issues or whatnot), then you solve your problem differently, by using features of Bash and sed
to fix your existing command, as follows:
Most special characters, such as newlines and whatnot, seem to be just fine inside single-quoted strings. The only characters that should be a problem are '
(which would be interpreted as terminating the string) and \
(which would be interpreted as introducing an escape sequence), and both of these can be addressed by prefixing a \
(for example, '\''
and '\\'
are string literals denoting '
and \
, respectively). This sed
script inserts a \
before any '
or \
:
s/\('\|\\\)/\\\1/g
which you can invoke from Bash like this:
sed 's/\('"'"'\|\\\)/\\\1/g' filename
(for example, if filename
contains this:
a \ b \ c
d ' e ' f
then sed 's/\('"'"'\|\\\)/\\\1/g' filename
will print this:
a \\ b \\ c
d \' e \' f
). But you can't just wrap the above in `...`
, because these characters are special to Bash as well, and it will get confused. (I'm assuming you're using Bash?) Instead, you need to use $(...)
, which is a Bash notation that's equivalent to `...`
except that it better handles various details like this. (I recommend always using $(...)
over `...`
.) So your overall command would be:
mysql -p -u user -e "update my_table set body='$(sed 's/\('"'"'\|\\\)/\\\1/g' filename)' where id=x;" dbname