Renaming .txt files in bulk - batch-file

I downloaded about 34000 books in .txt format from Project Gutenberg. Now I want to rename all of them by its content. For example every text file includes its "Title" and "Author's Name" so I want to rename all the text files on its "Title" and "Author's Name" by some commands.
I created a batch file. It runs but is not renaming the files. This is my code:
#echo off&setlocal
cd E:\Test
for /f "delims=" %%i in ('dir /a-d/b *.txt') do (
set "nname="
set "fname=%%~i"
for /f "usebackqskip=7delims=" %%f in ("%%~i") do if not defined nname
set "nname=%%f"
setlocal enabledelayedexpansion
set "nname=!nname:~0,40!"
echo rename "!fname!" "!nname!"
endlocal
)

You can use this as a base
#echo off
setlocal enableextensions disabledelayedexpansion
rem Change to source folder
pushd "e:\test" && (
rem Where the renamed files will be placed to avoid re-rename
if not exist renamed\ md renamed
rem For each input file
for %%f in (*.txt) do (
rem Retrieve the data from inside the file
set "author=" & set "title="
for /f "tokens=1,* delims=: " %%a in ('
findstr /b "Author: Title:" "%%~ff"
') do if not defined %%a set "%%a=%%b"
rem If the fields have been retrieved then do the rename
if defined author if defined title (
setlocal enabledelayedexpansion
for /f "delims=" %%a in ("!author! - !title!") do (
endlocal
echo move "%%~ff" "renamed\%%a%%~xf"
rem NOTE: operation is only echoed to console
rem if console output seems correct, then
rem remove the echo command
)
)
)
rem Done. Return to previous active directory
popd
)
Of course, filesystem has rules about what is allowed in a file name and, not knowing what kind of characters can be found, this code could and probably will fail to rename some files.

Your current script will just print the rename commands, not execute them. You should remove echo (after checking what it produces) in this line:
echo rename "!fname!" "!nname!"
Your script also has a few formatting issues. There should be spaces like this:
for /f "usebackq skip=7 delims=" %%f in ("%%~i") do
And there should be no newline just after:
if not defined nname

Related

Creating List of Folders from File Names

I have a folder containing many files named as such: JBMA_23456.docx, JMRI_21456.docx, CM_22554.docx, QUA_11224.docx. How do I create a sub-folder for each file bearing the same name as the file but without the .docx file extension? Additionally, I want to store the filename only as variables.
For example, I need to create a sub-folder named JBMA_23456 from the document
JBMA_23456.docx. Can anyone point me in teh right direction?
#echo off
for %%A in (*.docx) do if not exist "%%~nA" md "%%~nA"
This creates a folder with the same name as each .docx file.
View modifiers in for /? or in call /?. The n modifier is the name.
Path modifiers:
dpnx is drive, path, name and extension.
Here's an example batch file which attempts to perform the tasks as laid out in your question:
#Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "BaseDir=C:\Users\Compo\Desktop\test"
Set "FileExt=.docx"
For /F "Delims==" %%A In ('Set var[ 2^>Nul') Do Set "%%A="
Set "i=0"
For /F "Delims=" %%A In ('Where "%BaseDir%":*%FileExt% 2^>Nul') Do (Set /A i+=1
Call Set "var[%%i%%]=%%~nA"
If Exist "%%~dpA%%~nA\" (Echo Sub-Folder %%~nA already exists in %BaseDir%
) Else (Set /P "=Creating sub-folder %%~nA in %BaseDir%"<Nul
MD "%%~dpA%%~nA">Nul 2>&1 && (Echo= was successful) || Echo= failed))
Set var[ 2>Nul
Pause
In order to use it, you would first ensure that the directory holding your files, (excluding any trailing backslash), is placed between the = and " on line 4, and the single file extension, (including the leading period, .), similarly on line 5.
It is not entirely clear what you are asking for...
Anyway, here is the code i made
echo off
chcp 65001
cls
for /f "usebackq delims=." %%0 in (`dir /b "*.docx"`) do (
set filename=%%0
md %filename%
)
cmd /k
It creates a new folder for every file. Feel free to ask if this was not what you expected

Batch script to pick filename from a text file and find the latest file

Scenario:
We have multiple releases of a product, and for each release, a folder is created in the main folder. A help file is modified in various releases. I have all the help file names listed in a text file.
I need a script to:
Take each file name from the filenames.txt file
Search for the file by that name in the entire directory (in all releases)
Find the latest file
Copy it to a specified folder
I took help from the various pieces of code I found on Stack Overflow, and combined them to get this code:
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
echo.
FOR /F "usebackq delims=" %%a in ("filenames.txt") do (
SET "x=%%a"
ECHO '!x!'
SET FFPath=C:\SVN\nlbavwdocsvn\rep_doc_erpln\trunk\ERPLN
SET NewPath=C:\Lavanya\extracted
SET NewestDate=20160824
ECHO Recursively searching %FFPath%
FOR /F %%I in ('DIR %FFPath%\ !x! /a:-d /s /b') DO (
SET FullDate=%%~tI
ECHO %FFPath%
REM Set CurrDate to yyyymmdd format. Note: Will fail if regional settings changed.
SET CurrDate=!FullDate:~6,4!!FullDate:~0,2!!FullDate:~3,2!
If !CurrDate! gtr !NewestDate! (
SET NewestDate=!CurrDate!
SET NewestFile=%%~fI )
ECHO Copying %NewestFile% to %NewPath%
ECHO.
COPY /Y "%NewestFile%" "%NewPath%"
ECHO.
)
)
PAUSE
This code is not working. And I am unable to figure out the error.
Here is a script to search for the most recently modified file, using the wmic command to retrieve the last modification date/time in a locale-independent manner (e. g., 20160824115500.000000+060).
So for every file name read from the list file .\filenames.txt, the directory tree routed at directory C:\SVN\nlbavwdocsvn\rep_doc_erpln\trunk\ERPLN is searched for matching files recursively, and the respective modify date/time stamp is gathered. Due to its format, a simple greater-than (GTR) comparison can be done do determine whether or not it is a later point of time than a cached one; if the criterion is fulfilled, the cache is updated accordingly.
The upper-case REM and ECHO commands constitute placeholders only for the real action to be performed on the files. Extend the script there as you like. Variable !LASTFILE! holds the full path to each encountered file.
So here is the code:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "LOCATION=C:\SVN\nlbavwdocsvn\rep_doc_erpln\trunk\ERPLN"
set "FILELIST=.\filenames.txt"
set "WMICPROP=LastModified" & rem // {CreationDate | LastAccessed | LastModified}
pushd "%LOCATION%" || exit /B 1
for /F "usebackq eol=| delims=" %%L in ("%FILELIST%") do (
set "LASTFILE="
set "LASTFAGE=00000000000000.000000+000"
for /F "eol=| delims=" %%F in ('dir /B /S /A:-D "%%~L"') do (
set "FILE=%%F"
setlocal EnableDelayedExpansion
set "FILE=!FILE:\=\\!"
for /F "tokens=2 delims==" %%J in ('
2^> nul wmic DataFile WHERE ^(Name^="!FILE!"^) GET %WMICPROP% /VALUE ^|^| ^
2^> nul wmic DataFile WHERE Name^="!FILE!" GET %WMICPROP% /VALUE
') do for /F %%I in ("%%J") do (
endlocal
set "FAGE=%%I"
setlocal EnableDelayedExpansion
if !FAGE! GTR !LASTFAGE! (
endlocal
set "LASTFILE=%%F"
set "LASTFAGE=%%I"
setlocal EnableDelayedExpansion
)
)
endlocal
)
if defined LASTFILE (
setlocal EnableDelayedExpansion
REM Do whatever you want with the file here...
ECHO Newest file: "!LASTFILE!"
endlocal
)
)
popd
endlocal
exit /B

Changing folder name with names from a file using batch

I want to write a batch script to rename folders in a directory.
The way that would work is, I would have a file that contains names that I would like each folder to be renamed with. So basically the batch script would just pick names from the file (that contains names) and use it to rename each folder.
So if I have 20 folders, 20 names would exist in file to rename each folder.
What I have so far:
#echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET old=*.txt
SET new="c:\Users\user\Desktop\testing.txt"
< %new% (for /f "tokens=*" %%f in ('dir /b %old%') do (
ren Read the next name from the redirected input file
SET /P newname=
ren "%%f" "!newname!"
))
The above script didn't give me the desired result.
Not tested:
#echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET old=*.txt
SET new="c:\Users\user\Desktop\testing.txt"
set counter=0
(for /f "tokens=*" %%f in ('dir /b %old%') do (
ren Read the next name from the redirected input file
set /a counter=counter+1
for /f "tokens=1* delims=:" %%a in ('findstr /R /N "^" "%new%"^|find "!counter!"') do set "newname=%%b"
ren "%%f" "!newname!"
)
The problem is that the dir /b %old% command generate a list of files with .txt extension. If you want to rename folders, then include /AD switch and eliminate the wild-card:
#echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET new="c:\Users\user\Desktop\testing.txt"
< %new% (for /f "tokens=*" %%f in ('dir /b /AD') do (
ren Read the next name from the redirected input file
SET /P newname=
ren "%%f" "!newname!"
))

How to find the occurrence of comma in a report of txt format and replace it with space using batch script

I have a many reports which is in a txt format in D:\folder\data\data1.The occurrence of comma is not predictable.Where ever the comma is found inside the txt file i need to replace with a space.so i have to do this for more than one text file
For example: The data in report will be like
abacndl 123455 300,90.55 aldfankas 400,123,455.900
adsmnfnka 12345774 134,789.9 aeraermk 456,987,87.000
and like wise it goes on
Could some one please help me in doing a batch script for this scenario
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\sourcedir\t w o"
PUSHD "%sourcedir%"
FOR %%a IN (*.txt) DO (
FOR /f "usebackq delims=" %%b IN ("%%a") DO (
SET "line=%%b"
>>"%%~na.XTX" echo(!line:,= !
)
)
rem delete existing text files and renam new version to .txt
del *.txt
ren *.xtx *.txt
popd
GOTO :EOF
You would need to change the setting of sourcedir to suit your circumstances.
change to the target directory,
for each .txt file, read each line to %%b, save that in line for processing, and output line processed to substitute each , with Space
The name chosen for the new output file is %%~na.xtx - that is, the original name with a new extension xtx. In this way, you can easily check the new format before using. I'm assuming no .xtx files exist before the run.
I don't understand the problem with del/ren above; it works perfectly for me.
Here's another version - only the rename code is different.
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\sourcedir\t w o"
PUSHD "%sourcedir%"
FOR %%a IN (*.txt) DO (
FOR /f "usebackq delims=" %%b IN ("%%a") DO (
SET "line=%%b"
>>"%%~na.XTX" echo(!line:,= !
)
)
rem rename new version to .txt - alternative codeline
FOR %%a IN (*.xtx) DO (MOVE /y "%%~na.XTX" "%%~na.txt") >nul
popd
GOTO :EOF

Renaming text files by reading last word of 2nd line

I have a large number of text files.
I need a batch script that reads each file, and renames it to the last word of second line.
The last word of 2nd line of these text files is unique within the given set of files.
#ECHO OFF
SETLOCAL
SET "sourcedir=."
FOR /f "delims=" %%a IN ('dir /b /a-d "%sourcedir%\*.txt"') DO (
SET "found="
FOR /f "skip=1delims=" %%b IN ('type "%sourcedir%\%%a"') DO IF NOT DEFINED found (
SET "found=%%b"
SETLOCAL ENABLEDELAYEDEXPANSION
SET "found=!found:"=!"
SET "found=!found: =.!"
FOR /f %%c IN ("!found!") DO SET "found=%%~xc"
ECHO REN "%sourcedir%\%%a" "!found:~1!.txt"
ENDLOCAL
)
)
GOTO :EOF
The required REN commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO REN to REN to actually rename the files.

Resources