【发布时间】:2020-02-08 04:25:33
【问题描述】:
我编写了一个 shell 脚本 (.sh) 文件,它将 SQL 查询的结果存储到一个文件中。
SQL 文件的结果需要批量转换为 INSERT 查询。
SQL 查询中有三列,使用以下命令将它们写入文件
mysql -u$db_user -p -h 127.0.0.1 -P 3308 < my_query.sql > my_results_into_file
现在我对文件my_results_into_file进行一些操作
sed -i.bak -e $'s/\t/\x27,\x27/g' my_results_into_file # replace tabs in output with commas, add single quotes around values
sed -i.bak -e '1d' my_results_into_file # remove first line from the file (column names)
sed -i.bak -e $'s/^/INSERT INTO mytable(column1, column2, column3) VALUES(\x27/' my_results_into_file # build inserts
sed -i.bak -e $'s/$/\x27);/' my_results_into_file # build inserts
上面的脚本会导致一个问题,因为Query中有一个NULLABLE列,它可以包含NULL,这将使NULL值被单引号括起来,被视为'NULL'并且是一个字符串。
有没有一种方法可以在其中一个脚本中避免在 NULL 周围加上单引号???
【问题讨论】:
标签: sql bash shell file scripting