如果最后一个字符是分号,使用批处理文件将行与下一行合并

5
我有一个包含以下4行的文件。
A;1;abc;<xml/>;
;2;def;<xml
>hello world</xml>;
;3;ghi;<xml/>;

使用批处理文件,我需要组合行,使得如果该行不以分号(;)结尾,则将下一行合并到当前行中。
因此,所需输出应为:
A;1;abc;<xml/>;
;2;def;<xml>hello world</xml>;
;3;ghi;<xml/>;

我对批处理脚本不是很熟悉,但尝试使用了for /F,但目前还没有成功。

据我所知,逻辑应该是检查每行的最后一个字符,如果不是分号,则将下一行读入当前行。

此外,我设法获取了行的最后一个字符,但我的脚本只有在行不以分号开头时才读取该行。有什么想法吗?

@echo off
for /f "tokens=*" %%i in (myfile.txt) do (
  set var=%%i
  echo %%i
  if "%var:~-1%"==";" (
    echo test
  )
)

注意:上述查询仅读取第1行和第3行。
3个回答

7
您的代码存在一些问题 :)
1)正如您所说,您的代码忽略以“;”开头的行 - 这是由于默认的FOR /F EOL选项引起的。但是,由于“TOKENS = *”,您的代码也会剥离每行的前导空格。您需要将EOL和DELIMS都设置为“nothing”。语法很奇怪,但它能够工作:
for /f delims^=^ eol^= %%i ...

2) 你试图在一个括号代码块中设置和扩展变量。这是不可能的,因为当解析该行时会发生扩展,并且整个代码块将一次性解析。因此%var%的值是在循环执行之前存在的值,显然这不是你想要的。解决方案是使用延迟扩展。在命令提示符下键入FOR /?以获取有关延迟扩展的更多信息(在帮助列表的中间位置)。

3) 对于包含!的变量内容,在启用延迟扩展时进行扩展会导致内容被破坏。解决方案是根据需要在循环内部切换延迟扩展的开关。但这会导致一个复杂的问题,因为你需要跨ENDLOCAL屏障保留正在增长的行的值。我使用FOR /F在屏障上运输值。

以下是应该能够完成任务的完整批处理脚本。它的局限性在于无法处理大于约8191字节的行。

为修复一个重要的错误,已重新编写了这段代码

@echo off
setlocal disableDelayedExpansion
set "ln="
set "print=0"
for /f delims^=^ eol^= %%i in (myfile.txt) do (
  set "var=%%i"
  setlocal enableDelayedExpansion
  for /f delims^=^ eol^= %%A in ("!ln!!var!") do (
    if "!var:~-1!"==";" (
      endlocal
      echo %%A
      set "ln="
    ) else (
      endlocal
      set "ln=%%A"
    )
  )
)

SET /P 解释:

有一种更简单的解决方案,它立即打印每一行,因此您不必担心在 ENDLOCAL 间传输变量。行末没有 ; 的行将使用 SET /P 打印而无需换行。

这种解决方案有以下限制:

1) 通过 SET /P 打印的行将删除前导空格。此限制仅适用于 Vista 和更新版本的 Windows。在 XP 上不是问题。

2) 感谢 David Ruhmann,我现在知道如果行以 = 开头,则 SET /P 将失败。非常不幸 :(

@echo off
setlocal disableDelayedExpansion
set "ln="
for /f delims^=^ eol^= %%i in (myfile.txt) do (
  set "var=%%i"
  setlocal enableDelayedExpansion
  if "!var:~-1!"==";" (echo !var!) else (<nul set /p ="!var!")
  endlocal
)

混合批处理/JScript正则表达式解决方案(强大且稳定)

我编写了一个名为REPL.BAT的混合批处理/JScript实用程序,可以轻松进行文件内容的正则表达式搜索和替换。使用它可以使工作变得非常容易。

下面的命令应该对任何输入都有效,没有限制。它已经更新,支持Windows和Unix样式的行。并且它比纯批处理解决方案快得多。

findstr "^." myfile.txt|repl "([^;\r])\r?\n" "$1" m >"outFile.txt"

这里是REPL.BAT实用程序。完整文档已嵌入脚本中。

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

另外补充一点,我正在使用的输入文件是CSV记录列表。 - Junaid
@Junaid - 你不应该遇到递归限制。听起来你的代码缺少一个ENDLOCAL。我不知道如何使第一种解决方案适用于超过8191字节的行。尝试第二个解决方案。希望你要么在XP上,要么不必担心前导空格。 - dbenham
@Junaid - 抱歉,你是正确的。我的第一个解决方案中有一个重大的错误。我重写了代码以修复错误并编辑了答案。 - dbenham
@Junaid - 我认为我的最终混合批处理/JScript解决方案是你最好的选择。 - dbenham
你有没有想过将第二个解决方案转换为UNIX需要多长时间?这会有多难? - Junaid
显示剩余4条评论

4

没有延迟扩展

@echo off
setlocal EnableExtensions DisableDelayedExpansion
for /f "tokens=* eol=" %%L in (myfile.txt) do (
    <nul set /p ="%%L" 2>nul                         %= Fixed Limitation 3 =%
    set "xLine=%%L"
    call set "xLine=%%xLine:"=%%"                    %= Fix for Limitation 2 =%
    call :NewLine
)
endlocal
pause >nul
goto :eof

:NewLine
if "%xLine:~-1%"==";" echo.
goto :eof

With Delayed Expansion

@echo off
setlocal EnableExtensions DisableDelayedExpansion
for /f "tokens=* eol=" %%L in (myfile.txt) do (
    <nul set /p ="%%L" 2>nul                         %= Fixed Limitation 3 =%
    setlocal EnableDelayedExpansion
    set "xLine=%%L"
    set "xLine=!xLine:"=!"                           %= Fix for Limitation 2 =%
    if "!xLine:~-1!"==";" echo.
    endlocal
)
endlocal
pause >nul

限制:(两个版本相同)

  1. 由于<nul set /p "=%%L" 命令的原因,行不能以等号=字符开头。
  2. 由于if "<var>"==";" echo. 命令的原因,行不能以双引号"字符结尾。
  3. 由于<nul set /p "=%%L" 命令的原因,在行首的双引号"字符会丢失。(已被dbenham解决)
  4. 由于"tokens=* eol="选项或Windows Vista或更新版本下的delims^=^ eol^=选项与set /p命令的原因,行首的空格将被删除。我选择实现tokens方法以保持所有Windows版本的一致性。
  5. 批处理行长度限制为8191字节。请参见Line length limit in xp batch file?http://support.microsoft.com/kb/830473

注意:这些限制不会导致脚本崩溃,但是1和3会导致跳过这些行,4只会删除行首的空格。

更新

我已经找到了set /p 命令引起的=等号和空格删除问题的(仅显示!)解决方案。但是,它需要在批处理脚本中输入一个非显示字符。这必须通过编辑脚本的十六进制数据来完成。放置任何非空格、非问题字符(用.表示),然后跟随退格字符(用0x08表示),只有%Var% 的值将显示。注意:这不适用于文件输出作为解决方案,因为非显示字符也会输出到文件中。

set /p =".0x08%Var%"

这个等号问题的原因是因为set命令在解析变量名时存在问题,不允许等号包含在变量名内。

set命令不允许等号成为变量名的一部分。

虽然这个问题一直存在,但随着Vista+中添加了前导空格修剪功能,该问题变得更加复杂。了解详细信息请参考:http://www.dostips.com/forum/viewtopic.php?f=3&t=4209

1
+1,我忘记了引号的问题。这可以通过将代码中的引号移动到等号后来解决:set /p ="%%L"。但是天哪,SET /P = 的问题对我来说是新的,而且很讨厌:( 在将代码引号移动到等号后面之后,我发现它只会在行以 =" 开头时出现问题。不跟随引号的以 = 开头的行可以正常工作。 - dbenham
1
哎呀 - 你关于 SET /P 和等号的说法是正确的。我自己骗了自己。当行以 = 开头时,它总是失败。 - dbenham
@dbenham 感谢您提到将引号放在等号后面的建议。 set / p ="%%L" 这至少解决了限制3的问题。 :) 关于等号 = 的问题,我还没有找到一个简单的解决方案。 - David Ruhmann
@dbenham 我刚刚也注意到了这个问题,正在努力修复。谢谢。**:)** - David Ruhmann
1
@Junaid 要将结果输出到文件,请使用重定向 file.bat>output.txt 调用批处理脚本,或在输出文本的行中添加重定向 >>output.txt 到批处理脚本中。不幸的是,批处理的限制为8191字节(8191 ASCII或2047 Unicode)。请参阅 https://dev59.com/JmHVa4cB1Zd3GeqPkTOe 和 http://support.microsoft.com/kb/830473。 - David Ruhmann
显示剩余3条评论

0

这里有一个解决方案,它不使用set /P命令,因为这会引入一些限制。在这里,适用的行被连接到一个变量中,并在遇到尾随分号时立即输出,使用echo没有这样的限制。代码包含解释性注释:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "FILE=%~1" & rem // (input file from command line argument)
set "CHAR=;"   & rem // (character that marks the end of line)

rem // Initialise variables:
set "PREV=" & rem // (variable to collect lines to combine)
rem // Iterate through the lines of the given file:
for /F usebackq^ delims^=^ eol^= %%L in ("%FILE%") do (
    set "LINE=%%L"
    rem // Toggle delayed expansion to not lose `!` in text:
    setlocal EnableDelayedExpansion
    rem // Check last character of current line:
    if "!LINE:~-1!"=="%CHAR%" (
        rem /* Last character marks end of line, so output
        rem    collected previous lines and current one: */
        echo !PREV!!LINE!
        rem // Clear Cached previous lines:
        endlocal
        set "PREV="
    ) else (
        rem /* Last character does not mark end of line, so
        rem    do not output it but cache it in a variable;
        rem    the `for /F` loop lets the data pass `endlocal`: */
        for /F delims^=^ eol^= %%K in ("!PREV!!LINE!") do (
            endlocal
            set "PREV=%%K"
        )
    )
)
rem /* Output all remaining cached data in case the last line
rem    is not terminated by an end-of-line marker: */
if defined PREV (
    setlocal EnableDelayedExpansion
    echo !PREV!
    endlocal
)

endlocal
exit /B

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接