Rename file with a string contained in the file

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
pc3d
Posts: 1
Joined: 11 May 2017 19:54

Rename file with a string contained in the file

#1 Post by pc3d » 11 May 2017 19:58

I have a file named 'psgl_extract.txt' that I want renamed with the string within the file. The string AURNTRNA20170509V141 is located in the first row of the file. Please help me with a batch file code ? Both batch file and target file will be in the same directory, d:\abc

Extract from file:

00AURNTRNA20170509V141

01RNET 201705090010020030000 7158254 562009 AUD-00000000000000000000000.020 200300009502015 03955711000283 01RNET 201705090010020030000 2347394

Desired Output:

AURNTRNA.20170509.V141.txt

Cheers, PC

Compo
Posts: 600
Joined: 21 Mar 2014 08:50

Re: Rename file with a string contained in the file

#2 Post by Compo » 12 May 2017 04:52

It seems a lot of work to rename just one file! Can you not open it copy the first line close it and rename with an edited paste.

That said here are some solutions using assumed information regarding the structure you have provided:

Code: Select all

@Echo Off
If Not Exist "D:\abc\psgl_extract.txt" GoTo :EOF
Set/P "_S="<"D:\abc\psgl_extract.txt"
For /F "Tokens=1 Delims=0123456789" %%A In ("%_S%") Do (Set "_A=%%A"
   For /F "Tokens=*" %%B In ('Call Echo^=%%_S:*%%A^=%%') Do Set "_N=%%B")
Ren "D:\abc\psgl_extract.txt" "%_A%.%_N:~,8%.%_N:~8%.txt"


If there are several .txt files in the same directory all with the same assumed structure then you may be able to use this:

Code: Select all

@Echo Off
SetLocal EnableDelayedExpansion
For %%A In (*.txt) Do (
   Set/P "_S="<"%%A"
   For /F "Tokens=1 Delims=0123456789" %%B In ("!_S!") Do (Set "_A=%%B"
      For /F "Tokens=*" %%C In ('Echo^=!_S:*%%B^=!') Do Set "_N=%%C")
   Ren "%%A" "!_A!.!_N:~,8!.!_N:~8!%%~xA")

Post Reply