【问题标题】:Replacing the sequence \r\r\n with the \r\n in batch file用批处理文件中的 \r\n 替换序列 \r\r\n
【发布时间】:2020-03-31 10:00:51
【问题描述】:

我需要创建一个批处理文件来执行一个工具来生成一些文件,然后将这些文件传递给其他一些工具。

但问题是第一个工具生成\r\r\n 的序列应该是换行符。所以我需要用 \r\n 替换这些序列。

1.txt

line number 1

line number 2

line number 4

line number 5

我试过这种方法

@ECHO OFF

SETLOCAL EnableDelayedExpansion

SET "SEARCH_TEXT=`r"
SET "REPLACE_TEXT="
FOR /f "delims=" %%A IN (1.txt) DO (
    SET "string=%%A"
    SET "modified=!string:%SEARCH_TEXT%=%REPLACE_TEXT%!"
    ECHO !modified!>>"2.txt"
)

但它只用\r\n替换\r\n\r\n

谁能帮我解决这个问题?

【问题讨论】:

  • 我打赌文本文件内容的来源是wmic 命令。无论如何,以下工作:(for /F "delims=" %%L in ('findstr /N "^" "1.txt"') do @for /F "tokens=1* delims=:" %%E in ("%%L") do @echo(%%F) > "2.txt"(虽然这会删除前导冒号,但这可以在需要时轻松解决)...
  • 非常感谢!有用。正是我想要的。
  • 不客气!请考虑accept答案然后...

标签: windows batch-file replace cmd line-breaks


【解决方案1】:

在尝试使用 for /F 循环将 Unicode 文本转换为 ASCII/ANSI 文本时,可能会出现此类额外的(孤立的)回车字符。一个经典的例子是通过for /F 循环捕获wmic 命令的Unicode 输出。

要摆脱这些转换伪影,只需添加一个额外的 for /F 循环:

@echo off
rem // Change to target directory (the parent of this script, for instance):
cd /D "%~dp0."
rem // Write output to file:
> 2.txt (
    rem // Loop through lines of file, prefix each with ine number plus `:`:
    for /F "delims=" %%L in ('findstr /N "^" 1.txt') do (
        rem /* Use another loop to get rid of additional carriage-return characters;
        rem    the `tokens` and `delims` options split off the line number prefix: */
        for /F "tokens=1* delims=:" %%E in ("%%L") do (
            rem // Output current line with the line number prefix removed:
            echo(%%F
        )
    )
)

cmets 中提到的临时行号前缀(行号加冒号)旨在不丢失空行,因为for /F 会忽略此类。然后,内部循环使用tokens 和delims 选项在for /F 处理该行后删除前缀。这也将从行中删除任何前导冒号。如果这真的可能发生,则将内部循环更改为 this 以保留这些::

        rem // Use another loop to get rid of additional carriage-return characters:
        for /F "delims=" %%E in ("%%L") do (
            rem // Store current line:
            set "LINE=%%E"
            rem // Toggle delayed expansion to avoid trouble with `!`:
            setlocal EnableDelayedExpansion
            rem // Output current line with the line number prefix removed:
            echo(!LINE:*:=!
            endlocal
        )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-23
    • 2011-09-18
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    相关资源
    最近更新 更多