Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ember.js/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Command line Windows命令行>;编辑文本文件中的特定字符串(包含等号)_Command Line_Windows Xp_Replace - Fatal编程技术网

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

Command line Windows命令行>;编辑文本文件中的特定字符串(包含等号),command-line,windows-xp,replace,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 我需要在这个文本文件中搜索一些特定的行,假

我花了一些时间在stackoverflow和整个网络上寻找一个描述良好的答案来解决这个问题

我有一个可以自行安装并读取.ini文件的软件。ini的大小和行号可变。每行的样式如下所示:

setting1=contents
setting2=more,contents
setting3=different type of contents
setting4=youget/theidea
Username=Tommy
Servername=HAL2000
我需要在这个文本文件中搜索一些特定的行,假设如下所示:

setting1=contents
setting2=more,contents
setting3=different type of contents
setting4=youget/theidea
Username=Tommy
Servername=HAL2000
然后替换等号后的值(即将Tommy更改为Timmy)。我的问题是,我发现并尝试合并的所有脚本要么将上述值视为变量(即用户名变为值为“Tommy”的变量),要么当我将Tommy替换为timmy时,.ini文件最终将文件中的每一行替换为username=Tommy

我已经删除了这两个脚本并继续,但是我越想它,我就越想回去做这个脚本


唯一的规则是,必须在Windows命令行中使用XP自带的命令。没有第三方程序,没有python,没有perl,只有Windows命令行可以在.bat文件中运行。

这会很笨拙,但是如果要替换的密钥数量有限,以下内容可能就足够了:

@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

a_horse_with_no_name解决方案非常适合您的需求。通过消除呼叫,它可以变得不那么笨拙,效率更高。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-loop解决方案可以扩展以支持这一点,但它会变得更加复杂和缓慢

您从未明确说明行的顺序是重要的-通常情况下.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"
批处理确实是一个处理文本文件的糟糕平台。它通常是缓慢和过于复杂的。看起来您的文件很小,而且您的需求相对简单。但许多看似简单的请求在纯批处理中是一件很难完成的事情

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/?
来访问文档。脚本应该位于当前目录中,或者位于路径中的其他位置

@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));
    }
  }
}

没有第三方程序哦,天哪,我可以使用一些linux命令,比如
awk
?笨手笨脚的会很好用。我将对此进行测试,并让您知道它是如何工作的。这个程序是为一个令人愉快的混乱,使用微软访问。。。除了记录都存储在SQL数据库中之外。。。程序将它们从SQL转换为Access。。。并且仍然以基于SQL的方式发布广告。。。与此无关,但我认为任何具备SQL知识的人都知道这有多糟糕。大约有2-4个变量需要更改,所以是的-范围非常有限。我正在努力自己纠正这个问题,因为您给了我很多工作要做,但是现在脚本只回显了.ini中的3行,与我想要的内容无关,它没有改变我想要更改的内容。值得进一步解释的是,我不想只在用户名为Tommy时才更改用户名的值。我想每次都更改用户名的值。Servername也一样,继续使用该示例。我想将Servername更改为HAL2001,无论脚本运行时它的值是多少。此外,它不会保存所做的更改(如果有)。@inconcorouserudite要始终更改服务器名和用户名,只需删除嵌套的if(请参阅我的编辑)。更改保存到另一个文件(即
outfile=newfile.ini
部分)。你不能覆盖你正在读取的文件。我一直在努力,并且完全意识到你刚才告诉我的,但是是我自己。我觉得自己很有成就;)脚本运行得很好,只是我完全没有注意到它正在保存newfile.ini而没有覆盖另一个.ini。不管怎样,我都把它修好了。谢谢你的帮助-我会给你打电话,但我自己的电话不够:(