2017-10-18 266 views
0

我试图分裂在文本文件中的条目,它的格式为:使用引号,以显示在上面的代码空间Windows批处理文件 - 分割字符串与特定的字符或空格作为分隔符

"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" 

谢谢你们,真的厌倦了批处理。

+2

检查修剪右功能 - http://www.dostips.com/DtTipsStringManipulation.php#Snippets.TrimRightFOR – npocmaka

+1

@npocmaka我爱你的男人。太感谢了。 – user3839914

回答

1

还有就是for /F loop将字符串拆分为某个分隔符。由于您有两个标记单个分隔符的字符(即两个空格),因此您可以用单个字符替换这些不能在字符串中其他位置出现的字符;例如,可以使用|,因为它在文件路径/名称中是不允许的。这是怎么可能看起来像:

@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 
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引用与一个结束反斜杠

元件的驱动器和路径通过添加.到先前路径和RETR ieving它的完整路径,我们删除结束反斜杠(除非路径是一个驱动器的根目录)

要保存的加工线,你只需要重定向输出

@echo off 
    setlocal enableextensions disabledelayedexpansion 

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