批处理:将双引号之间的 .txt 中的字符串写入 .txt

Batch: Write String from .txt between double quotes to .txt

我正准备编写一个批处理文件以从文本文件中获取行,并将两个“”(双引号)之间的内容写入另一个文本文件。

e.q。文件输入:

    WRITE    1,48,1,"1> MODUL 2 TYPENKONTROLLE "
    WRITE    1,56,1,"2> MODUL 6 PRAEGETIEFE    "
    Some other text...
    WRITE    1,64,1,"__________________________"

文件输出:

    "1> MODUL 2 TYPECONTROLE   "
    "2> MODUL 6 PRAEGETIEFE    "
    "__________________________"

我的不工作批次:

@echo File:
set /p file=
FOR /F delims^=^" %%i in ('findstr -i -r -c:"[\"]^" %file%.txt') do (
echo %%i >> %file%strings.txt 
)

我想我需要这样的东西:

@echo File:
set /p file=
FOR /F delims^=^" tokens^=1,2 %%i in ('findstr -i -r -c:"[\"]^" %file%.txt') do (    
echo %%i not needed!
echo %%j >> %file%strings.txt 
)

有人可以帮我解决我的问题吗?

最简单的解决方案是使用 grep。您需要 binaries and dependencies。那你就可以

grep -E -o "\".+\"" infile.txt > outfile.txt

得到你想要的输出。

在纯批处理中完成此操作的困难在于批处理将引号视为标记定界符。一些包含重定向符号(> 符号)的行进一步使事情复杂化。虽然把引号和>符号当成独立的字符并不容易,但是是可以的。

@echo off
setlocal

>outfile.txt (
    (
        for /f "usebackq delims=" %%I in ("infile.txt") do (
            call :get_stuff_between_quotes %%I
        )
    )
)

goto :EOF
:: // END MAIN RUNTIME

:: // get_stuff_between_quotes function
:: // echoes stuff between (and including) quotation marks
:: // echoes nothing if no quotation marks in argument
:get_stuff_between_quotes
:: // use delayed expansion to prevent evaluation of >
setlocal enabledelayedexpansion
set line=%*

:: // strip everything before first quotation mark
set line=!line:*"=!

:: // if line is unchanged, it didn't contain quotation marks.
if "!line!"=="%*" endlocal & goto :EOF

:: // otherwise, re-echo the leading quotation mark + the rest of the line
echo("!line!
endlocal & goto :EOF

虽然,在我看来,grep 解决方案更容易理解。

如果您正在寻找纯批处理解决方案,那么这可能就是您所需要的。它在 FOR /F 选项中使用难看的转义序列,以允许将 " 指定为您的标记分隔符。

@echo off
>"output.txt" (
  for /f usebackq^ tokens^=2^ delims^=^" %%A in ("input.txt") do echo "%%A" 
)

如果您想确保收盘价存在,那么您可以将 FINDSTR 添加到您的 DO 子句中。 FINDSTR 希望引号转义为 \".

@echo off
>"output.txt" (
  for /f usebackq^ tokens^=2^ delims^=^" %%A in ('findstr \".*\" "input.txt"') do echo "%%A" 
)

以上解决方案只写入任何行中第一个引用的字符串。忽略其他带引号的字符串。

但我通常使用 JREPL.BAT regular expression text utility 来处理文本。它是一个混合 JScript/batch 脚本,可以在任何 Windows XP 以后的机器上本地运行。

假设您的 PATH 包含一个包含 JREPL.BAT 的文件夹,那么您所需要的只是命令行中的以下内容:

jrepl "\q.*?\q" [=12=] /x /jmatch /f input.txt /o output.txt

由于 JREPL 是一个批处理脚本,如果您在另一个批处理脚本中使用该命令,则需要使用 CALL JREPL。

请注意,上述 JREPL 解决方案将每个带引号的字符串写在单独的行中,即使在同一源代码行中有两个带引号的字符串也是如此。如果你只想要任何行中第一个引用的字符串,那么解决方案就变成了

jrepl "(\q.*?\q).*"  /x /jmatch /f input.txt /o output.txt