标题: [文本处理] [已解决]批处理怎样把字符串分割并重组? [打印本页]
作者: slovent 时间: 2015-1-15 01:33 标题: [已解决]批处理怎样把字符串分割并重组?
本帖最后由 slovent 于 2015-1-15 09:28 编辑
想咨询如何将mysql里的insert语句重组为delete语句。
原始脚本如下,脚本存放在insert.sql文本中
INSERT INTO `table1` (`field1`, `field2`, `field3`, `field4`) VALUES ('value1', 'value2', 'value3', 'value4');
INSERT INTO `table2` (`field1`, `field2`, `field3`, `field4`, `field5`, `field6`) VALUES ('value1', 'value2', 'value3', 'value4', NULL, 'value6');
......
希望通过批处理将上述脚本重组为如下格式,并输出到delete.sql文本中
DELETE FROM `table1` WHERE `field1`='value1' AND `field2`='value2' AND `field3`= 'value3' AND `field4`= 'value4' ;
DELETE FROM `table2` WHERE `field1`='value1' AND `field2`='value2' AND `field3`= 'value3' AND `field4`= 'value4' AND `field6`= 'value6' ;
......
里面还有个复杂的需求,就是如果碰到字段值为NULL的话(例如表2的field5字段的值为NULL),则忽略掉这个字段的条件,在delete语句中不用列出该条件。
不知道有那位老师可以伸手援助,万分感激。
作者: apang 时间: 2015-1-15 09:19
- @echo off
- (for /f "tokens=1-4 delims=()" %%a in (insert.sql) do (
- setlocal enabledelayedexpansion
- set "s=%%a"
- set "s=!s:INSERT INTO=DELETE FROM!WHERE"
- for %%i in (%%b) do set /a n+=1 & set "_!n!=%%i"
- for %%i in (%%d) do (
- set /a m+=1
- if /i "%%i" NEQ "NULL" (
- for %%j in (!m!) do set "s=!s! !_%%j!=%%i AND"
- )
- )
- echo,!s:~,-4!;
- endlocal
- ))>delete.sql
- pause
复制代码
作者: slovent 时间: 2015-1-15 09:28
apang老师,运行完美。谢谢 谢谢。术业有专攻啊,真是厉害。
作者: yiwuyun 时间: 2015-1-15 16:53
来个gawk的。- @echo off
- setlocal EnableDelayedExpansion
- set txt=insert.sql
- gawk "BEGIN{FS=\"\\(^|\\)^| \\(^|\\) ^|, ^| \";}{count=(NF-5)/2;printf(\"DELETE FROM %%s WHERE\",$3);for(i=1;i<=count;i++){if($(i+count+4)==\"NULL\")continue;if(i==count){printf(\" %%s=%%s;\n\",$(i+3),$(i+count+4));}else{printf(\" %%s=%%s AND\",$(i+3),$(i+count+4));}}}" !txt!
- pause
复制代码
欢迎光临 批处理之家 (http://www.bathome.net/) |
Powered by Discuz! 7.2 |