使用批处理自动化解析文件名

时间:2018-06-03 12:53:24

标签: parsing batch-file automation

这可能很简单,但我不是计算机语言专家。 我一直在互联网上寻找解决方案近3个小时。

假设我的所有mp3文件都标题为“艺术家名称 - Song.mp3的标题”我希望它输出到包含的txt文件中:
艺术家:艺术家姓名
歌曲:歌曲的标题

如何将文件名解析为用连字符分隔的两个部分?我一直在尝试使用批处理文件进行某种自动化以进行存档,这是我的代码,我坚持使用:

@echo off
for /r %%a in (*.mp3) do (
(
for %%b in ("%%~na") do echo ^Artist: %%~b
echo ^Song:
)>"%%~dpna.txt"
) 

2 个答案:

答案 0 :(得分:1)

如何将文件名解析为用连字符分隔的两个部分?

  

我希望它输出到包含以下内容的txt文件中:

Artist: Name of Artist
Song: Title of Song

使用以下批处理文件作为起点:

@echo off
setlocal enabledelayedexpansion
for /f "tokens=1,2 delims=-" %%i in ('dir /b name*') do (
  echo Artist: %%i 
  echo Song: %%j
 )>>file.txt
endlocal

使用示例:

> dir name*
 Volume in drive F is Expansion
 Volume Serial Number is 3656-BB63

 Directory of F:\test

03/06/2018  14:06                 0 Name of Artist - Title of Song.mp3
03/06/2018  14:07                 0 Name of Artist 1 - Title of Song 1.mp3
               2 File(s)              0 bytes
               0 Dir(s)  1,269,011,574,784 bytes free

> test

> type file.txt
Artist: Name of Artist
Song:  Title of Song.mp3
Artist: Name of Artist 1
Song:  Title of Song 1.mp3    
>

我希望它为每个mp3文件都有一个文本文件。那可能吗?

是使用以下批处理文件:

@echo off
setlocal enabledelayedexpansion
for /f "tokens=*" %%a in ('dir /b name*.mp3') do (
  set _filename=%%~dpna.txt
  for /f "tokens=1,2 delims=-" %%i in ("%%a") do (
    echo Artist: %%i 
    echo Song: %%j
    )>!_filename!
  )
endlocal

使用示例:

> dir *.mp3
 Volume in drive F is Expansion
 Volume Serial Number is 3656-BB63

 Directory of F:\test

03/06/2018  14:06                 0 Name of Artist - Title of Song.mp3
03/06/2018  14:07                 0 Name of Artist 1 - Title of Song 1.mp3
               2 File(s)              0 bytes
               0 Dir(s)  1,269,022,654,464 bytes free

> test

> type name*.txt

Name of Artist - Title of Song.txt


Artist: Name of Artist 1
Song:  Title of Song 1.mp3

Name of Artist 1 - Title of Song 1.txt


Artist: Name of Artist 1
Song:  Title of Song 1.mp3

答案 1 :(得分:0)

更改PushD之后的起始文件夹以适应您的环境。

:: Q:\Test\2018\06\03\SO_50666632.cmd
@echo off
PushD "%USERPROFILE%\Music" || (Echo can't locate folder&Pause&exit /B 1)

for /r %%a in (*.mp3) do (
    if exist "%%~dpna.txt" (
        Echo "%%~dpna.txt" already present, skip
    ) else (
       for /f "tokens=1,*delims=-" %%b in ("%%~na") do (
           echo Artist: %%b
           echo Song  :%%c
       )>"%%~dpna.txt"
    )
)

我的ramdrive上的示例输出a:

> tree /F
Auflistung der Ordnerpfade
Volumeseriennummer : 5566-7788
A:.
│   Name of Artist - Title of Song.mp3
│   Name of Artist - Title of Song.txt
│
└───Music
        Survivor - Eye of the Tiger.mp3
        Survivor - Eye of the Tiger.txt


> type "Name of Artist - Title of Song.txt"
Artist: Name of Artist
Song  : Title of Song

> type "Music\Survivor - Eye of the Tiger.txt"
Artist: Survivor
Song  : Eye of the Tiger