batch code to chnage folders name after read text files

让人想犯罪 __ 提交于 2019-12-24 20:19:57

问题


Someone great in this site give me this code at batch change folder name by read line from text file

@echo off
pushd "your root location"  
for /f "tokens=1* delims=:" %%A in (  
'findstr /srbc:"SMTP_Email_Address  *type=SZ  *[^ ][^ ]*@[^ ][^ ]*\.[^ ][^ ]*  *SMTP_Email_Address" filel.txt^|sort /r'  
) do if exist "%%A" for %%F in ("%%A\..") do (  
  for /f "tokens=3" %%N in ("%%B") do ren "%%~fF" "%%N"  
)  
popd

the code find this code perfectly

SMTP_Email_Address type=SZ name@company.com SMTP_Email_Address

I want the code find this

<SMTP_Email_Address type="SZ">abc@abc.com</SMTP_Email_Address>

because of this signs > < "" the code not work

and change the folder name by the email found in the text file inside


回答1:


i think i understand the question. you need to escape the special characters with the caret sign (^) e.g. replace

"SMTP_Email_Address  *type=SZ  *[^ ][^ ]*@[^ ][^ ]*\.[^ ][^ ]*  *SMTP_Email_Address"

with

"^<SMTP_Email_Address  *type=^"SZ^"^>  *[^ ][^ ]*@[^ ][^ ]*\.[^ ][^ ]*  *^<^/SMTP_Email_Address^>"



回答2:


The following will work as long as the relevant line of XML is formatted exactly as you have specified. But that is risky, because the format of the XML could change and still be valid, yet it would break this code. Batch is not a good choice for parsing XML unless you know exactly how the XML will be formatted.

EDIT - this original code mostly worked, but it has 2 problems:

1) The sort operation can lead to the use of the wrong matching address line. It is supposed to use the first found matching line.

2) The script may attempt to rename the root location. Windows will not allow that because your batch script has its current directory set to that location.

@echo off
pushd "your root location"
for /f "tokens=1,3 delims=:<>" %%A in (
  'findstr /srbc:"<SMTP_Email_Address .*>[^ ][^ ]*@[^ ][^ ]*\.[^ ][^ ]*</SMTP_Email_Address>" file1.txt^|sort /r'
) do if exist "%%A" for %%F in ("%%A\..") do ren "%%~fF" "%%B"
popd


The code below has been fixed to properly use the first matching address line. It also will not attempt to rename the root location. But other renames could fail if any process currently has a dependency on that location.

@echo off
setlocal
pushd "YourRootLocation"
set "search=<SMTP_Email_Address .*>[^ ][^ ]*@[^ ][^ ]*\.[^ ][^ ]*</SMTP_Email_Address>"
for /f "eol=: delims=" %%A in (
  'findstr /srmbc:"%search%" file1.txt^|sort /r'
) do for /f "tokens=2 delims=<>" %%B in (
  'findstr /rbc:"%search%" "%%A"'
) do if exist "%%A" for %%F in ("%%A\..") do if "%%~fF" neq "%CD%" (
  echo ren "%%~fF" "%%B"
  ren "%%~fF" "%%B"
)
popd


来源:https://stackoverflow.com/questions/14232263/batch-code-to-chnage-folders-name-after-read-text-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!