我有一个包含以下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行。
答案 0 :(得分:6)
您的代码存在许多问题:)
1)正如您所说,您的代码会忽略以;
开头的行 - 这是由于默认的FOR / F EOL选项。但是由于“TOKENS = *”,您的代码也会从每一行中删除前导空格。您需要将EOL和DELIMS都设置为空。语法很奇怪,但它有效:
for /f delims^=^ eol^= %%i ...
2)您尝试在带括号的代码块中设置和扩展var。这不起作用,因为解析行时会发生扩展,并且会立即解析整个代码块。因此%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正则表达式解决方案(防弹?)
我编写了一个混合批处理/ JScript REPL.BAT实用程序,可以轻松进行正则表达式搜索并替换文件内容。它使工作变得非常简单。
以下命令应适用于任何输入,没有限制。它已更新为支持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));
}
}
}
答案 1 :(得分: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
@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
<nul set /p "=%%L"
命令,行可能不会以等于 = 字符开头。if "<var>"==";" echo.
命令,行可能不会以双引号&#34; 字符结尾。<nul set /p "=%%L"
命令,该行开头的双引号&#34; 字符将丢失。"tokens=* eol="
选项,将修剪该行开头的空格。由于delims^=^ eol^=
命令,对于使用set /p
选项的Windows Vista或更新版本,会出现同样的问题。我选择在所有版本的Windows中实现tokens
方法的一致性。注意:这些限制都不会导致脚本崩溃,但是1和3会导致跳过这些行,4只会修剪该行的前导空格。
我找到=
命令导致的set /p
等于和空间修剪问题的解决方案(仅显示!)解决方案。但是,它要求在批处理脚本中输入非显示字符。这必须通过编辑脚本的十六进制数据来完成。放置任何非空格,非问题字符(由.
说明)后跟退格字符(由0x08
说明),只显示%Var%
的值。 注意:这不能作为文件输出的解决方案,因为非显示的字符也将输出到文件。
set /p =".0x08%Var%"
这等于问题的原因是因为set
命令在解析变量名时遇到问题,并且不允许将equals包含在变量名中。
SET命令不允许等号成为变量名称的一部分。
此问题一直存在,但Vista +中添加的领先空间修剪问题更加复杂。好的分析:http://www.dostips.com/forum/viewtopic.php?f=3&t=4209
答案 2 :(得分: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