【问题标题】:batch split filename on regex在正则表达式上批量拆分文件名
【发布时间】:2017-07-31 01:07:23
【问题描述】:

我被分配了一项任务,按艺术家和歌曲名称对歌曲进行分类。 给了我歌曲文件,我不得不通过分隔符(' - ')(空格连字符空格)将艺术家的名字从文件中取出。

歌曲:
Artist.A - 歌曲 1.wav
艺术家 B - song-2.wav
艺术家---C - song$B.mp3
Artists$D - song-4.mp3

到目前为止,这是我想出的,但我无法获得字符串“Artists B”:

dir /b "C:\songs\" | for /f "delims=" %a ('findstr /c:" - "') do ( echo %a )

它获取 C:\songs\ 下的歌曲,并确保它们包含“ - ”。

我对批处理还是很陌生,阅读了“for”的“man”页面,但我找不到答案。
我还查找了与 %a: - :^&REM #% 相关的内容,但是无法让它工作。

希望有人可以帮助我。

【问题讨论】:

  • 是的,如果他们是艺术家姓名中的其他连字符,这可能会很棘手。如果艺术家名和歌曲名之间只有一个连字符,那将没有问题。
  • 是的,如果是这样,答案就是“delims=-”
  • 使用JREN.BAT - jren "^.+? - +" ""

标签: regex batch-file split


【解决方案1】:

for /F command 使用字符来分割字符串,而不是字符串。 findstr command 不会拆分字符串,它总是返回包含匹配项的完整行。

鉴于艺术家姓名不包含 SPACE + - + SPACE,您可以将该子字符串替换为单个字符,这不会出现在文件名(例如,|),然后在该字符处拆分字符串,使用for /F,如下所示:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_LOCATION=C:\songs"
set "_MASK=* - *.*"

rem // Loop through the matching files:
for /F "usebackq eol=| delims=" %%F in ('
    dir /B /A:-D "%_LOCATION%\%_MASK%"
') do (
    rem // Store the pure file name:
    set "FILE=%%~nF"
    rem // Toggle delayed expansion to not lose exclamation marks:
    setlocal EnableDelayedExpansion
    rem // Replace ` - ` by `|` and split the file name at the first `|`:
    for /F "tokens=1* delims=|" %%A in ("!FILE: - =|!") do (
        endlocal
        rem // Store the artist, which is the first file name portion:
        set "ARTIST=%%A"
        setlocal EnableDelayedExpansion
        rem // Extract song title, which is all behind the first ` - `:
        set "SONG=!FILE:* - =!"
        rem // Return the result:
        echo(Artist: !ARTIST!
        echo(Title:  !SONG!
    )
    endlocal
)

endlocal
exit /B

【讨论】:

    【解决方案2】:
    @ECHO Off
    SETLOCAL ENABLEDELAYEDEXPANSION
    SET "sourcedir=U:\sourcedir"
    FOR /f "delims=" %%a IN (
     'dir /b /a-d "%sourcedir%\* - *" '
     ) DO (
     SET "fulltitle=%%a"
     SET "song=!fulltitle:* - =!"
     CALL SET "artist=%%fulltitle: - !song!=%%"
     ECHO artist=!artist!
     ECHO song  =!song!
     ECHO TITLE =!fulltitle!
     ECHO ------------------
    )
    
    GOTO :EOF
    

    您需要更改sourcedir 的设置以适应您的情况。

    /b 基本形式/a-d 不带目录执行dir 命令,并将找到的名称分配给%%a

    %%a 复制到fulltitle 以允许子串。已调用 delayedexpansion 以允许访问变量的运行时值。找到每个名称后,标题将是出现在- 之后的完整标题部分,因此将“whatever -”替换为nothing。然后使用call 将“ - thetitle”替换为空,以允许被替换的部分是可变的,留下艺术家姓名。

    报告结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-05
      • 2022-01-17
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      相关资源
      最近更新 更多