You have got some nasty tricky issues to deal with.
Problem 1: \ and " must be escaped as \\ and \" for FINDSTR. But special characters must be either escaped or quoted for the CMD.EXE parser. You enclose your search string in quotes, so the special characters are OK, except you want to include a quote in your search string. That creates unpaired quotes and everything becomes more complicated. The simple solution is to use two escaped quotes \"\" in your character set expression. It keeps the quotes paired, and doesn't do any harm to have the same character appear twice in the set. Now all the special characters are quoted from the perspective of CMD.EXE, so you don't need to escape them.
Problem 2: You are attempting to pass unescaped special characters through a pipe. The solution for this is very ugly. You can't execute the command directly. Instead you store the line in a variable and execute the command via CMD with /V:ON option to enable delayed expansion. It is critical that delayed expansion be disabled in your parent batch so that the value is not expanded until it gets inside the new CMD session.
Code: Select all
for /f "eol=/ delims=" %%a in (format.txt) do (
set "test=%%a"
cmd /v:on /c echo !test!|findstr /r "[/\\:*?\"\"<>|]" >nul
if errorlevel 1 (
set "format=%%a"
) else (
cls
echo Your format contains illegal characters!
echo Rename not completed.
pause
exit
)
)
The above works, but it is very slow.
I'm not sure what your requirements are. But the following might help you develop a faster and simpler solution:
This code will only match lines that are valid format that don't begin with /
Code: Select all
findstr /r "^[^/\\:*?\"\"<>|]*$" format.txt
This code will only match lines that don't begin with / that contain illegal characters
Code: Select all
findstr /r "^[\\:*?\"\"<>|] ^[^/].*[/\\:*?\"\"<>|]" format.txt
When using findstr, you can use the following syntax to check the results. I much prefer this over checking ERRORLEVEL.
Code: Select all
findstr "search" file >nul && (echo match found) || (echo no match found)
Dave Benham