Batch - String replacement with special characters

2019-07-03 03:57发布

I would like to replace a string in a file using a batch file.

The string is:

),(

And I want to replace it by:

),
(

I found several posts, like this one : "how-to-replace-substrings-in-windows-batch-file" but the example uses a dummy string with no special characters.

Thank you !

EDIT

Context: I use mysqldump to extract a database and I would like every line of the insert command to be on a new line for more visibility.

I don't want to use --extended-insert=false because it slows down reinsertion of the backup.

EDIT2

Example:

INSERT INTO `dummytable` (`dummycolumn`) VALUES (1),(2),(3);

I want it to be:

INSERT INTO `dummytable` (`dummycolumn`) VALUES (1),
(2),
(3);

3条回答
放我归山
2楼-- · 2019-07-03 04:07

Take a look at replacer.bat

call replacer.bat "e?C:\content.txt" "\u0022),(\u0022" "\u0022),\u000a(\u0022"

Edit without the quotes:

call replacer.bat "e?C:\content.txt" "),(" "),\u000a("

windows style

call replacer.bat "e?C:\content.txt" "),(" "),\u000D\u000a("

you can check also FindRepl and JRepl which are more sophisticated tools

查看更多
Ridiculous、
3楼-- · 2019-07-03 04:15

This works for me:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET textFile=test.txt
TYPE NUL>tempOut.txt
FOR /F %%l IN (%textFile%) DO (
    SET line=%%l
    SET line=!line:"),("="),\n("!
    ECHO !line!>>tempOut.txt
)
MOVE /y tempOut.txt %textFile%
查看更多
我想做一个坏孩纸
4楼-- · 2019-07-03 04:23

In batch if the pattern are always same you could deal with tokens and delims like this:

@echo off

(echo INSERT INTO `dummytable` (`dummycolumn`^) VALUES (1^),(2^),(3^);
)>%TEMP%\_file.tmp

(FOR /F "tokens=1,2,3* delims=," %%a IN (%TEMP%\_file.tmp) do (
    echo %%a,
    echo %%b,
    echo %%c
))>_output.txt
exit /b 0

output:

INSERT INTO `dummytable` (`dummycolumn`) VALUES (1),
(2),
(3);

Edit
I found another way from a npocmaka's post in stackoverflow

@echo off

setlocal disableDelayedExpansion
REM Creating a Newline variable (the two blank lines are required!)
set NLM=^


set NL=^^^%NLM%%NLM%^%NLM%%NLM%

setlocal enableDelayedExpansion

for /f "delims=" %%a in (%TEMP%\_file.tmp) do (
    set "line=%%a"
    set line=!line:,(=,%NL%(!
    echo !line!
)

endlocal
endlocal
exit /b 0
查看更多
登录 后发表回答