Wednesday, May 2, 2018

Replace character in variable within batch script

I wanted to rename a file using a batch script so it would replace underscores '_' with hyphens '-'. It was pretty easy

Set img1=this-was_the_original-name-of_the_file
Set newName=%img1:_=-%
echo %newName%

The key to doing it is the :_=- in the second line, which is saying take the text value stored in the variable img1 and make underscores instead equal hyphens. Now, you could make line 2 instead be

Set img1=%img1:_=-%

If you don't need to reference the original value you're storing in img1 later, but for my purposes I was renaming a file so I needed both the original filename and what the new filename should be, so I had to store the new name with the hyphens in a separate variable

No comments:

Post a Comment

Hi, thanks for choosing to leave a comment. Please make sure that it's relevant to the topic you're commenting on though. If you're just trying to promote another product or webpage, sorry, but your comment will be deleted.