Batch CMD - 提取文本直到最后一个特殊字符

Batch CMD - Extract text upto last special character

我正在尝试提取没有文件名的路径位置。例如,程序生成的日志文件将具有类似于以下的字符串:

2021-03-24T13:34:15 - Processing: C:\Source\SubFolder1\SubFolder2\SubFolder3\File1-???????????.txt

我需要从日志文件中提取的内容如下:

C:\Source\SubFolder1\SubFolder2\SubFolder3

到目前为止我能得到:

C:\Source\SubFolder1\SubFolder2\SubFolder3\File1-???????????????????????.txt"

使用以下代码:

for /f "delims=" %%a in ('^<"C:\Source0\sample.txt" find "Processing:"') do set _path="%%a"

set _path_=%_path:~35%

echo %_path_%

请帮助我演示如何省略 File1*-?????字符串的一部分

编辑:文件 1-??????部分的字符长度不固定,子目录也不是可以在级别上进一步下降。唯一固定的部分是我使用 %_path:~35%.

省略的字符串的前 35 个字符

也许这样的事情对你有用:

as a 中:

For /F "Tokens=3,*" %G In ('%SystemRoot%\System32\find.exe "Processing:" 0^<"C:\Source0\sample.txt"') Do @For %I In ("%~dpH.") Do @Echo %~dpnxI

或作为 in a :

@For /F "Tokens=3,*" %%G In ('%SystemRoot%\System32\find.exe "Processing:" 0^<"C:\Source0\sample.txt"') Do @For %%I In ("%%~dpH.") Do @Echo %%~dpnxI

我很高兴你有一些有用的东西。另一种方法是使用支持的 Windows 系统上已有的 PowerShell。这看起来很长,但可以通过不仔细检查日期和时间来缩短。

SET "THESTRING=2021-03-24T13:34:15 - Processing: C:\Source\SubFolder1\SubFolder2\SubFolder3\File1-???????????.txt"

REM === Find the full file name
SET "PART=no match"
FOR /F "delims=" %%A IN ('powershell -NoLogo -NoProfile -Command ^
    "if ('%THESTRING%' -match '\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2} - Processing: .*\(.*)\.txt.*') {" ^
    "$Matches[1]"}') DO (SET "PART=%%~A")
ECHO PART IS ===%PART%===

REM === Find the part of the name after the HYPHEN character
SET "PART=no match"
FOR /F "delims=" %%A IN ('powershell -NoLogo -NoProfile -Command ^
    "if ('%THESTRING%' -match '\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2} - Processing: .*\.*-(.*)\.txt.*') {" ^
    "$Matches[1]"}') DO (SET "PART=%%~A")
ECHO PART IS ===%PART%===

如果不是 运行 in CMD.EXE 就容易多了。

$TheSting=2021-03-24T13:34:15 - Processing: C:\Source\SubFolder1\SubFolder2\SubFolder3\File1-???????????.txt"
$Part = if ('%TheString%' -match '\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2} - Processing: .*\(.*)\.txt.*') { "$Matches[1]" }