1

I need to replace all occurrences of several characters in an argument to batch file:

helper.bat

@echo off echo %1 call:replace_newline_characters_and_additional_quotes arg %%1 echo %arg% goto:eof :replace_newline_characters_and_additional_quotes set in=%2 set tmp=%in:\n=|% set %1=%tmp:""=\"% goto:eof 

Run it as

helper "1""2\n3"

Output

"1""2\n3"
"3"" is not recognized as an internal or external command, operable program or batch file

What am i doing wrong?

4
  • What are you trying to achieve? Remove all quotes and replace newlines with | ? Commented Aug 2, 2013 at 10:33
  • @SmokeyPHP Replace all "" with \" and replace all \n with | Commented Aug 2, 2013 at 10:37
  • so you want output as: "1\"2|3" ? Commented Aug 2, 2013 at 10:43
  • @SmokeyPHP In this case, yes Commented Aug 2, 2013 at 10:43

2 Answers 2

3
set str=%1 set str=%str:""=\"% set str=%str:\n=^|% echo %str:|=^|% pause 

Just worked for me with your test case.

You get the "3"" is not recognized error because of the pipe | character, as it means that CMD is trying to pass the text before the | to the 'program' after it, which is why you'll notice I've used ^| to 'escape' the pipe and stop it from having it's special meaning

Sign up to request clarification or add additional context in comments.

Comments

3

You should switch to delayed expansion, as it's safe to use special characters.

setlocal EnableDelayedExpansion set "param1=%1" echo !param1! call :replace_newline_characters_and_additional_quotes arg param1 echo !arg! exit /b :replace_newline_characters_and_additional_quotes set "in=!%2!" set "tmp=!in:\n=|!" set "%1=!tmp:""=\"!" exit /b 

The only problematic line is set "param1=%1", as it would fail in the case of calling

helper "&"^& 

And it's not easy to avoid this, but there exists a solution at
SO: Get list of passed arguments in Windows batch script

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.