Windows批处理文件 - 将包含某些字符或空格的字符串拆分为分隔符

时间:2017-10-18 05:55:03

标签: string batch-file cmd whitespace

我正在尝试拆分文本文件中的条目,格式为:

"C:\Software\New folder\New folder\New folder\New folder\OneDrive - Test   "
"C:\Software\New folder\New folder\New folder\New folder\OneDrive - Test  "
"C:\Software\New folder\New folder\New folder\New folder\OneDrive - Test     "

使用引号显示上面代码中的空格。简单来说,我的文本总是以两个或更多的空格结束。

所以我想将分隔符设为,(是两个空格),所以我的最终输出应该是

"C:\Software\New folder\New folder\New folder\New folder\OneDrive - Test"

使用引号显示空格

或者,我也知道字符串中的最后一个字总是One Drive - Test

即使我可以使用下面的格式拆分输出,然后我可以使用One Drive - Test附加到每一行

"C:\Software\New folder\New folder\New folder\New folder"

谢谢你们,真的厌倦了Batch。

2 个答案:

答案 0 :(得分:1)

如果您的所有行都遵循显示的模式,那么您可以处理文件引用而不是尝试处理字符串

@echo off
    setlocal enableextensions disabledelayedexpansion

    rem For each line in input file
    for /f "usebackq delims=" %%a in ("inputFile.txt") do (
        rem Retrieve the parent folder of the read reference
        for %%b in ("%%~dpa.") do (
            rem And echo it without the ending backslash (see the dot in the upper line)
            echo %%~fb
        )
    )

%%a将在迭代输入文件

时保留每条读取行

%%~dpa%%a中引用的元素的驱动器和路径,带有反斜杠

通过向前一个路径添加.并检索其完整路径,我们删除了结尾反斜杠(除非路径是驱动器的根目录)

要保存已处理的行,您只需要重定向输出

@echo off
    setlocal enableextensions disabledelayedexpansion

    >"outputFile.txt" (
        for /f "usebackq delims=" %%a in ("inputFile.txt") do (
            for %%b in ("%%~dpa.") do echo %%~fb
        )
    )

答案 1 :(得分:1)

for /F loop以某个分隔符分割字符串。由于您有两个标记单个分隔符的字符(即两个 SPACE ),您可以用字符串中其他位置不能出现的单个字符替换它们;例如,可以使用echo,因为文件路径/名称中不允许使用|。这就是它的样子:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Read input text file `txtfile.txt` line by line:
for /F "usebackq delims= eol=|" %%L in ("textfile.txt") do (
    rem // Store line string in environment variable:
    set "LINE=%%L"
    rem // Toggle delayed expansion to avoid loss of/trouble with exclamation marks:
    setlocal EnableDelayedExpansion
    rem /* Replace two-character delimiter by a single character:
    rem    (the `|| endlocal` suffix is only executed in case the current line contains
    rem    delimiters only, because the `for /F` loop would not execute in that case) */
    (for /F "delims=| eol=|" %%F in ("!LINE:  =|!") do (
        rem // Toggle back delayed expansion:
        endlocal
        rem /* Return part before first delimiter (actually this returns the very first
        rem    non-empty sub-string before the first (sequence of) delimiter(s), or,
        rem    if the string begins with (a) delimiter(s), the very first non-empty
        rem    sub-string between the first and second (sequences of) delimiters: */
        echo/%%F
    )) || endlocal
)

endlocal