批处理脚本来处理文件

时间:2012-08-06 13:32:02

标签: windows batch-file

我有一个配置文件,该文件就像 mach.conf

Machine_IP = <IP Address>
Machine_Name = <Machine name>
User_Name = <UID>
ERRORCODE = 8000
..

同样。我是Windows批处理脚本的新手,虽然我已经在互联网上阅读了关于批处理脚本并且能够理解&amp;编写简单的批处理脚本但是我找不到使用批处理脚本处理文件的地方,比如我想看看配置文件,如果我看到ERRORCODE = 8000 做一个更改并用8001替换8000。

如何使用批处理脚本执行此操作。请提供链接或一些提示。

...谢谢

1 个答案:

答案 0 :(得分:1)

我添加了一些可能没有必要的代码,但允许程序操作不带引号的&lt; &gt; &#39;第所有这一切都是为他们预先添加 ^ ,因此&lt; 变为 ^&lt; &gt; 变为 ^&gt;

@echo off
 setlocal enabledelayedexpansion
 if exist config.tmp del config.tmp
 for /f "tokens=1* delims== " %%x in (config.cnf) do call :processFile "%%x" "%%y"
 move config.tmp config.cnf > nul
 echo File Updated
 endlocal
goto :eof

:processFile
 set "Var=%~1"
 set "Val=%~2"

 :: Add Escape Code to the greater-than and less-than symbols so they don't
 :: act as pipes and create errors.
 set "Var=%Var:<=^<%"
 set "Var=%Var:>=^>%"
 set "Val=%Val:<=^<%"
 set "Val=%Val:>=^>%"

 if "%Var%"=="ERRORCODE" set /a Val=%Val% + 1

 echo %Var% = %Val%>> config.tmp