Ok as the title says, i need a way to rename a text document, to the text there are in the text document, so if the document have this text (cake) then it need to rename the file name to cake.
Here is a pseudo code in batch that use a Regex with a vbscript in order to read and match the first word in the text file when reads from it, and then if the file is not empty, the script will rename your text file with the variable extracted from the vbscript.
How to test this code ?
Just Copy and paste this code below and save it as Rename-First-Word-Content.bat
and create a text file named Test.txt
in the same folder of your batch and write some words on it and save it. Finally just double click on the batch and see the result !
@echo off
Set "InputFile=Test.txt"
Call :Extract "%InputFile%" NewName
If defined NewName (
echo NewName = "%NewName%"
Ren "%InputFile%" "%NewName%.txt"
)
pause & exit
::-----------------------------------------------------------------------------------
:Extract <InputFile> <Variable NewName to be Set>
(
echo WScript.StdOut.WriteLine Extract(Data^)
echo Function Extract(Data^)
echo Dim strPattern,oRegExp,Matches
echo Data = "%~1"
echo Data = WScript.StdIn.ReadAll
echo strPattern = "[^-_\\/:;\x22*.?<>|]([\w\-]+)"
echo Set oRegExp = New RegExp
echo oRegExp.Global = False
echo oRegExp.IgnoreCase = True
echo oRegExp.Pattern = strPattern
echo set colMatches = oRegExp.Execute(Data^)
echo For Each Match in colMatches
echo Content = Match.Value
echo Next
echo Extract = Content
echo End Function
)>"%tmp%\%~n0.vbs"
@For /f "delims=" %%i in ('cscript //nologo "%tmp%\%~n0.vbs" ^< "%~1" 2^>nul') do Set "%2=%%i"
If Exist "%tmp%\%~n0.vbs" Del "%tmp%\%~n0.vbs"
Exit /B
::----------------------------------------------------------------------------------