You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shell脚本生成SQL INSERT语句缺失引号问题求助

Shell脚本生成SQL INSERT语句缺失单引号问题解决

问题说明

需求是读取文件中的数字,生成符合以下格式的SQL INSERT命令:

INSERT INTO `opensips`.`usr_preferences`(`uuid`, `username`, `domain`, `attribute`, `type`, `value`, `last_modified`) VALUES ('1111111111', '1111111111', 'mydomain.com', 'fs', 2, '8.8.8.8', NOW());

但实际生成的语句中,字符串类型的字段(uuid、username、domain、attribute、value)都缺失了单引号,结果如下:

INSERT INTO `opensips`.`usr_preferences`(`uuid`, `username`, `domain`, `attribute`, `type`, `value`, `last_modified`) VALUES (1111111111, 1111111111, mydomian.com, fs, 2, 8.8.8.8, NOW());

原脚本代码:

echo "Removing Carriage"

#Remove carriage from file 

sed 's/\r$//' update.txt > forprocessing.txt 

sleep 1

echo "Generating Output"

sleep 2

#Generate Output

echo ""
file="forprocessing.txt"
while IFS= read line
do
#Add new routing rule
echo 'INSERT INTO `opensips`.`usr_preferences`(`uuid`, `username`, `domain`, `attribute`, `type`, `value`, `last_modified`'') VALUES ('$line', '$line', ''mydomian.com', 'fs', 2, '8.8.8.8',' NOW());'

done <"$file"
echo ""
echo "========"
echo "Finished"
echo "========"
#Clean up
rm forprocessing.txt

解决方法

问题出在echo语句的引号处理上:原脚本用单引号包裹整个字符串,导致内部单引号无法正确输出,且变量解析逻辑混乱。修改后的脚本如下:

echo "Removing Carriage"

# Remove carriage from file 
sed 's/\r$//' update.txt > forprocessing.txt 

sleep 1

echo "Generating Output"

sleep 2

# Generate Output
echo ""
file="forprocessing.txt"
while IFS= read line
do
    # Add new routing rule
    echo "INSERT INTO `opensips`.`usr_preferences`(`uuid`, `username`, `domain`, `attribute`, `type`, `value`, `last_modified`) VALUES ('$line', '$line', 'mydomain.com', 'fs', 2, '8.8.8.8', NOW());"
done <"$file"
echo ""
echo "========"
echo "Finished"
echo "========"
# Clean up
rm forprocessing.txt

关键修改点

  1. 引号调整:将echo的外层单引号改为双引号,这样可以正常解析变量$line,同时直接在需要单引号的字段前后添加单引号(如'$line'会输出为'1111111111')。
  2. 修正语法错误:删除了原脚本中last_modified后的多余单引号,修正为正确的)。
  3. 拼写修正:将域名mydomian.com改为正确的mydomain.com。

内容的提问来源于stack exchange,提问作者gareth0402

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 09:24:26