Click here for important information about Computing.net.

How to rename text files based on text strings in the files

January 24, 2021 at 01:35:13
Specs: Windows 10
I have thousands of text files with arbitrary names that I would like to rename based on text within the files. Each file has lines that begins with "Title: " and "Author: ", e.g.

Title: The Greatest Book Ever Written
Author: Authory McAuthorson

Those strings are not always on the same line number in the file.

I would like to change the file name to:
The Greatest Book Ever Written, Authory McAuthorson.txt

All of the text files can be in the same directory. Sounds hard. Thanks for your thoughts.


See More: How to rename text files based on text strings in the files


#1
January 25, 2021 at 02:37:24
:: ren file title - author from lines in file
::====== script starts here ===============
::
:: TA.bat 2021-01-25 16:27:55.65
@echo off & setLocal enableDELAYedeXpansioN

:main
for /f "tokens=* delims= " %%a in ('dir/b *.txt') do ( call :sub1 %%a )
goto :eof

:sub1
for /f "tokens=* delims= " %%i in ('find "Title: " ^< "%*"') do (
set T=%%i & set T=!T:Title: =!
)

for /f "tokens=* delims= " %%i in ('find "Author: " ^< "%*"') do (
set A=%%i & set A=!A:Author: =!
)
echo ren "%*" "!T!- !A!.TXT"
goto :eof
::====== script ends here =================

=====================

M2


Reply ↓  Report •

#2
January 26, 2021 at 02:25:01
That was amazing sir! You are a ninja. That worked perfectly on 27,258 of 32,448 files. It looks like most of the ones that failed either had illegal characters in the Title (e.g. : or "), were duplicates, or had the title broken across two lines so appeared to be duplicates, e,g.:

Title: Chicken Soup for the Hot Coder
____ Vol. 1 Batch Magic.
(the "_" are 7 spaces)

Thank you very much. I will search around to see if there is a smooth way to add duplicated detection and maybe append a number to the base title.

message edited by spindlehead


Reply ↓  Report •

#3
January 26, 2021 at 04:23:12
Yep, you can append a number to repeats.

And you can strip illegal chars.

As for title or author string over two lines, that's a mess.

=====================

M2


Reply ↓  Report •
Related Solutions


Ask Question