How do I replace an asterisk that is from MediaInfo metadata while using a Windows batch file

104 Views Asked by At

I am using mediainfo to pull metadata from an audio file and then use its information to generate a folder tree. Because this metadata allows for special characters such as astericks the folders cannot be generated. I can't seem to replace an asterisk using this script. I believe it might have to do with the fact that the * is a wildcard. Any thoughts or questions for me?

[mcve]

@echo off
setlocal enabledelayedexpansion
set "album_name=Make Sh*t Happen"
set "album_folder=!album_name:*=_!"
set album_folder
endlocal

I expect the following result:

album_folder=Make Sh_t Happen

I've tried a variety of different methods to try and replace the *, to no avail.

set "album_folder=!album_folder:^*=_!"

I'm definitely missing something.

2

There are 2 best solutions below

0
Magoo On

Been asked a number of times. No universal solution afaiaa.

You could use something like this:

SETLOCAL

SET "string=hello*this&is*a*string"
:loop
FOR /f "tokens=1*delims=&*" %%b IN ("%string%") DO IF "%%c" neq "" SET "string=%%b_%%c"&GOTO loop

SET str

It's not perfect, but might suffice for your application.

OTT, if you're able to use 3rd-party utilities, then sed or (g)awk could be a solution.

3
Gatorman On

My solution may not be pretty, but I finally got it to work. I export the mediainfo metadata to a txt file, then replace the asterisk with PowerShell. There is also a PowerShell command to Trim any spaces at the end of the line of the txt file.

for /f "delims=" %%b in ('%~dp0tools\mediainfo "--Inform=General;%%Performer%%" "%%a" 2^>nul') do (
        (echo %%b) > %~dp0tools\artist_name.txt && powershell -command "(get-content %~dp0tools\artist_name.txt) -replace '[\x2A]+', '_' | set-content %~dp0tools\artist_name.txt"
        set /p artist_name=<%~dp0tools\artist_name.txt
    )