Windows命令行>从文本文件中编辑特定字符串(包含等号)

时间:2012-10-26 17:44:18

标签: command-line windows-xp replace

我花了一些时间在stackoverflow和网络上寻找一个很好描述的问题答案。

我有一个安装自己并读取.ini文件的软件。此.ini具有可变大小和可变行号。每一行的风格如下:

setting1=contents
setting2=more,contents
setting3=different type of contents
setting4=youget/theidea

我需要在这个文本文件中搜索一些特定的行,让我们说它是以下内容:

Username=Tommy
Servername=HAL2000

然后在等号后面替换值(即将Tommy改为Timmy)。我的问题是,我发现并尝试合并的所有脚本都将上面的值看作变量(即用户名变为值为“Tommy”的变量)或者当我用timmy替换Tommy时,.ini文件最终用Username = Tommy替换文件中的每一行。

我已经删除了这两个脚本并继续前进,但我想的越多,我就越想回去做这个脚本。

只有规则才能在Windows命令行中使用XP本机命令。没有第三方程序,没有python,没有perl,只有Windows命令行可以用完.bat文件。

2 个答案:

答案 0 :(得分:1)

a_horse_with_no_name解决方案非常适合您的要求。通过消除CALL,可以减少笨拙和高效。 MOVE命令用于使用新数据覆盖原始文件。

@echo off
>"test.ini.new" (
  for /f "usebackq tokens=1* delims==" %%A in ("test.ini") do (
    if %%A==Username (
      echo %%A=Timmy
    ) else if %%A==Servername (
      echo %%A=HAL2001
    ) else echo %%A=%%B
  )
)
move /y "test.ini.new" "test.new"

以上假设文件中的每一行都符合您声明的格式。但通常.INI文件的注释行也不符合应保留的格式。可以扩展FOR循环解决方案以支持它,但它变得更复杂,更慢。

您从未明确声明行的顺序很重要 - 通常.INI文件中的行顺序并不重要。这是一个非常简单的解决方案,它使用FINDSTR去除现有的Username和Servername行,然后将新值附加到最后。无论格式如何,都将保留所有未更改的行。更改的行总是出现在最后。

@echo off
>"test.ini.new" (
  findstr /v "^Username= ^Servername=" "test.ini"
  echo Username=Timmy
  echo Servername=HAL2001
)
move /y "test.ini.new" "test.new"

Batch实际上是一个处理文本文件的糟糕平台。它通常很慢而且过于复杂。看起来您的文件很小,而且您的要求相对简单。但是许多看似简单的请求都是纯粹的野兽。

JScript在处理文本方面要好得多,而且它本身适用于XP及以上版本。它具有完整的正则表达式支持。我编写了一个混合批处理/ JScript实用程序脚本,可用于对文本文件的内容执行搜索和替换操作。它非常快速,功能强大且易于使用。您的问题的解决方案实现为:

@echo off
type "test.ini" | repl "^Username=.*$" "Username=Timmy" | repl "^Servername=.*$" "Servername=HAL2001" >"test.ini.new"
move /y "test.ini.new" "test.new"

或更简洁地说:

@echo off
type "test.ini" | repl "^(Username=).*$" "$1Timmy" | repl "^(Servername=).*$" "$1=HAL2001" >"test.ini.new"
move /y "test.ini.new" "test.new"

以下是REPL.BAT实用程序脚本。完整文档嵌入在脚本中。也可以通过键入REPL /?从命令提示符访问文档。该脚本应该位于当前目录中,或者位于PATH中的某个位置。

@if (@X)==(@Y) @end /* Harmless hybrid line that begins a JScript comment

::************ Documentation ***********
:::
:::REPL  Search  Replace  [Options  [SourceVar]]
:::REPL  /?
:::
:::  Performs a global search and replace operation on each line of input from
:::  stdin and prints the result to stdout.
:::
:::  Each parameter may be optionally enclosed by double quotes. The double
:::  quotes are not considered part of the argument. The quotes are required
:::  if the parameter contains a batch token delimiter like space, tab, comma,
:::  semicolon. The quotes should also be used if the argument contains a
:::  batch special character like &, |, etc. so that the special character
:::  does not need to be escaped with ^.
:::
:::  If called with a single argument of /? then prints help documentation
:::  to stdout.
:::
:::  Search  - By default this is a case sensitive JScript (ECMA) regular
:::            expression expressed as a string.
:::
:::            JScript syntax documentation is available at
:::            http://msdn.microsoft.com/en-us/library/ae5bf541(v=vs.80).aspx
:::
:::  Replace - By default this is the string to be used as a replacement for
:::            each found search expression. Full support is provided for
:::            substituion patterns available to the JScript replace method.
:::            A $ literal can be escaped as $$. An empty replacement string
:::            must be represented as "".
:::
:::            Replace substitution pattern syntax is documented at
:::            http://msdn.microsoft.com/en-US/library/efy6s3e6(v=vs.80).aspx
:::
:::  Options - An optional string of characters used to alter the behavior
:::            of REPL. The option characters are case insensitive, and may
:::            appear in any order.
:::
:::            I - Makes the search case-insensitive.
:::
:::            L - The Search is treated as a string literal instead of a
:::                regular expression. Also, all $ found in Replace are
:::                treated as $ literals.
:::
:::            E - Search and Replace represent the name of environment
:::                variables that contain the respective values. An undefined
:::                variable is treated as an empty string.
:::
:::            M - Multi-line mode. The entire contents of stdin is read and
:::                processed in one pass instead of line by line. ^ anchors
:::                the beginning of a line and $ anchors the end of a line.
:::
:::            X - Enables extended substitution pattern syntax with support
:::                for the following escape sequences:
:::
:::                \\     -  Backslash
:::                \b     -  Backspace
:::                \f     -  Formfeed
:::                \n     -  Newline
:::                \r     -  Carriage Return
:::                \t     -  Horizontal Tab
:::                \v     -  Vertical Tab
:::                \xnn   -  Ascii (Latin 1) character expressed as 2 hex digits
:::                \unnnn -  Unicode character expressed as 4 hex digits
:::
:::                Escape sequences are supported even when the L option is used.
:::
:::            S - The source is read from an environment variable instead of
:::                from stdin. The name of the source environment variable is
:::                specified in the next argument after the option string.
:::

::************ Batch portion ***********
@echo off
if .%2 equ . (
  if "%~1" equ "/?" (
    findstr "^:::" "%~f0" | cscript //E:JScript //nologo "%~f0" "^:::" ""
    exit /b 0
  ) else (
    call :err "Insufficient arguments"
    exit /b 1
  )
)
echo(%~3|findstr /i "[^SMILEX]" >nul && (
  call :err "Invalid option(s)"
  exit /b 1
)
cscript //E:JScript //nologo "%~f0" %*
exit /b 0

:err
>&2 echo ERROR: %~1. Use REPL /? to get help.
exit /b

************* JScript portion **********/
var env=WScript.CreateObject("WScript.Shell").Environment("Process");
var args=WScript.Arguments;
var search=args.Item(0);
var replace=args.Item(1);
var options="g";
if (args.length>2) {
  options+=args.Item(2).toLowerCase();
}
var multi=(options.indexOf("m")>=0);
var srcVar=(options.indexOf("s")>=0);
if (srcVar) {
  options=options.replace(/s/g,"");
}
if (options.indexOf("e")>=0) {
  options=options.replace(/e/g,"");
  search=env(search);
  replace=env(replace);
}
if (options.indexOf("l")>=0) {
  options=options.replace(/l/g,"");
  search=search.replace(/([.^$*+?()[{\\|])/g,"\\$1");
  replace=replace.replace(/\$/g,"$$$$");
}
if (options.indexOf("x")>=0) {
  options=options.replace(/x/g,"");
  replace=replace.replace(/\\\\/g,"\\B");
  replace=replace.replace(/\\b/g,"\b");
  replace=replace.replace(/\\f/g,"\f");
  replace=replace.replace(/\\n/g,"\n");
  replace=replace.replace(/\\r/g,"\r");
  replace=replace.replace(/\\t/g,"\t");
  replace=replace.replace(/\\v/g,"\v");
  replace=replace.replace(/\\x[0-9a-fA-F]{2}|\\u[0-9a-fA-F]{4}/g,
    function($0,$1,$2){
      return String.fromCharCode(parseInt("0x"+$0.substring(2)));
    }
  );
  replace=replace.replace(/\\B/g,"\\");
}
var search=new RegExp(search,options);

if (srcVar) {
  WScript.Stdout.Write(env(args.Item(3)).replace(search,replace));
} else {
  while (!WScript.StdIn.AtEndOfStream) {
    if (multi) {
      WScript.Stdout.Write(WScript.StdIn.ReadAll().replace(search,replace));
    } else {
      WScript.Stdout.WriteLine(WScript.StdIn.ReadLine().replace(search,replace));
    }
  }
}

答案 1 :(得分:0)

这将是笨拙的,但如果要更换的键数量有限,以下可能就足够了:

@echo off

set infile=foo.ini
set outfile=newfile.ini

rem create an empty output file
echo. > %outfile%

rem iterate over all properties
for /f " usebackq eol=# tokens=1,2 delims== " %%i in ("%infile%") do (
  call :replace %%i %%j
)

rem terminate batch file
goto :eof

rem sub-program to do the replacing
:replace

  if "%1"=="Username" (
    echo Username=Timmy>>%outfile%
    goto :eof
  )

  if "%1"=="Servername" (
    echo Servername=HAL2001>>%outfile%
    goto :eof
  )
  echo %1=%2>>%outfile%

  rem terminate sub-program
  goto :eof