I'm trying to write a batch file that will extract a zip file. (This part works) It should read the restoretranslation.conf file, which consists of two comma separated values. The first value is the file name, and the second is the file path where the respective file would reside, (if existing).
If value one exists in the extracted zip directory and is defined with a path in the conf file, it should prompt the user if they want to replace the file. If yes, backup the file in the path in the second value. (%%b in the conf file) to %%b\original_%%a. we should then replace the file.
It seems like most of my variables are not being parsed correctly. Could someone give me some pointers?
Here's an example of the data in the configuration file:
license.xml,C:\Program Files (x86)\programname
Script:
#echo on
rem Set the directory where the ZIP files are located
set zipfolder=%~dp0
setlocal enabledelayedexpansion
rem Get a list of all ZIP files in the directory that start with "RTSBACKUP-"
set cnt=0
for /f "delims=" %%a in ('dir /b /a-d "%zipfolder%RTSBACKUP-*.zip"') do (
set /A cnt+=1
set "zipfile=%%a"
set "zipfile=!zipfile:~0!"
echo !cnt! - !zipfile!
)
rem Prompt the user to select a file to extract
set /p "fileNum=Enter the number of the file you want to extract: "
rem Extract the selected file
set cnt=0
for /f "delims=" %%b in ('dir /b /a-d "%zipfolder%RTSBACKUP-*.zip"') do (
set /A cnt+=1
if !cnt!==%fileNum% (
set "zipfile=%%b"
echo %zipfile%
pause
set "zipfile=!zipfile:~0!"
start /min "***Compressing backup files...*** ***Do not close this window.***" /wait powershell Expand-Archive -LiteralPath "%zipfolder%%zipfile%" -DestinationPath "%zipfolder%%zipfile:~0,-4%"
echo The file %zipfile% has been extracted successfully!
goto :break
)
)
endlocal disabledelayedexpansion
:break
set extractedfolder=%zipfolder%!zipfile:~0,-4!\!zipfile:~0,-4!\
rem Set the location of the restoretranslation.conf file
set "resttranslationfile=%~dp0restoretranslation.conf"
rem Loop through all files in the extractedfolder
for /f "delims=" %%i in ('dir /b /a-d "%extractedfolder%*.*"') do (
set "file=%%~i"
rem Loop through the resttranslation.conf file
for /f "tokens=1,2 delims=," %%a in ("%resttranslationfile%") do (
if /i "!FILE!"=="%%a" (
set "dirto=%%b"
rem Ask for confirmation before restoring the file
set /p confirm=Do you want to restore %file% to %dirto%? (^Y/N^)^:
if /i "%confirm%"=="y" (
rem Backup the original file
echo Backing up original file to !extractedfolder!original_%file%
if exist "%dirto%\%file%" (
copy "%dirto%\%file%" "!extractedfolder!original_%file%"
)
rem Copy the backup file to the specified destination
echo Restoring !file! to %%b
copy "!extractedfolder!!file!" "%%b\"
)
)
)
)
pause
Output:
C:\Tyler>rem Set the directory where the ZIP files are located
C:\Tyler>set zipfolder=C:\Tyler\
C:\Tyler>setlocal enabledelayedexpansion
C:\Tyler>rem Get a list of all ZIP files in the directory that start
with "RTSBACKUP-"
C:\Tyler>set cnt=0
C:\Tyler>for /F "delims=" %a in ('dir /b /a-d
"C:\Tyler\RTSBACKUP-*.zip"') do ( set /A cnt+=1 set "zipfile=%a" set
"zipfile=!zipfile:~0!" echo !cnt! - !zipfile! )
C:\Tyler>( set /A cnt+=1 set
"zipfile=RTSBackup-RSC-ERIELAB2-01202023-171815.zip" set
"zipfile=!zipfile:~0!" echo !cnt! - !zipfile! ) 1 -
RTSBackup-RSC-ERIELAB2-01202023-171815.zip
C:\Tyler>rem Prompt the user to select a file to extract
C:\Tyler>set /p "fileNum=Enter the number of the file you want to
extract: " Enter the number of the file you want to extract: 1
C:\Tyler>rem Extract the selected file
C:\Tyler>set cnt=0
C:\Tyler>for /F "delims=" %b in ('dir /b /a-d
"C:\Tyler\RTSBACKUP-*.zip"') do ( set /A cnt+=1 if !cnt! == 1 ( set
"zipfile=%b" echo RTSBackup-RSC-ERIELAB2-01202023-171815.zip pause
set "zipfile=!zipfile:~0!" start /min "***Compressing backup
files...*** ***Do not close this window.***" /wait powershell
Expand-Archive -LiteralPath
"C:\Tyler\RTSBackup-RSC-ERIELAB2-01202023-171815.zip" -DestinationPath
"C:\Tyler\RTSBackup-RSC-ERIELAB2-01202023-171815" echo The file
RTSBackup-RSC-ERIELAB2-01202023-171815.zip has been extracted
successfully! goto :break ) )
C:\Tyler>( set /A cnt+=1 if !cnt! == 1 ( set
"zipfile=RTSBackup-RSC-ERIELAB2-01202023-171815.zip" echo
RTSBackup-RSC-ERIELAB2-01202023-171815.zip pause set
"zipfile=!zipfile:~0!" start /min "***Compressing backup files...***
***Do not close this window.***" /wait powershell Expand-Archive -LiteralPath "C:\Tyler\RTSBackup-RSC-ERIELAB2-01202023-171815.zip" -DestinationPath "C:\Tyler\RTSBackup-RSC-ERIELAB2-01202023-171815" echo The file RTSBackup-RSC-ERIELAB2-01202023-171815.zip has been
extracted successfully! goto :break ) )
RTSBackup-RSC-ERIELAB2-01202023-171815.zip Press any key to continue .
. . The file RTSBackup-RSC-ERIELAB2-01202023-171815.zip has been
extracted successfully
C:\Tyler>set extractedfolder=C:\Tyler\!zipfile:~0,-4!\!zipfile:~0,-4!\
C:\Tyler>rem Set the location of the restoretranslation.conf file
C:\Tyler>set "resttranslationfile=C:\Tyler\restoretranslation.conf"
C:\Tyler>rem Loop through all files in the extractedfolder
C:\Tyler>for /F "delims=" %i in ('dir /b /a-d
"C:\Tyler\RTSBackup-RSC-ERIELAB2-01202023-171815\RTSBackup-RSC-ERIELAB2-01202023-171815\*.*"')
do ( set "file=%~i" rem Loop through the resttranslation.conf file
for /F "tokens=1,2 delims=," %a in
("C:\Tyler\restoretranslation.conf") do (if /I "!FILE!" == "%a" ( set
"dirto=%b" rem Ask for confirmation before restoring the file set /p
confirm=Do you want to restore to ? (Y/N): if /I "" == "y" ( rem
Backup the original file echo Backing up original file to
!extractedfolder!original_ if exist "\" (copy "\"
"!extractedfolder!original_" ) rem Copy the backup file to the
specified destination echo Restoring !file! to %b copy
"!extractedfolder!!file!" "%b\" ) ) ) )
C:\Tyler>( set "file=License.xml" rem Loop through the
resttranslation.conf file for /F "tokens=1,2 delims=," %a in
("C:\Tyler\restoretranslation.conf") do (if /I "!FILE!" == "%a" ( set
"dirto=%b" rem Ask for confirmation before restoring the file set /p
confirm=Do you want to restore to ? (Y/N): if /I "" == "y" ( rem
Backup the original file echo Backing up original file to
!extractedfolder!original_ if exist "\" (copy "\"
"!extractedfolder!original_" ) rem Copy the backup file to the
specified destination echo Restoring !file! to %b copy
"!extractedfolder!!file!" "%b\" ) ) ) )
C:\Tyler>(if /I "!FILE!" == "C:\Tyler\restoretranslation.conf" ( set
"dirto=" rem Ask for confirmation before restoring the file set /p
confirm=Do you want to restore to ? (Y/N): if /I "" == "y" ( rem
Backup the original file echo Backing up original file to
!extractedfolder!original_ if exist "\" (copy "\"
"!extractedfolder!original_" ) rem Copy the backup file to the
specified destination echo Restoring !file! to copy
"!extractedfolder!!file!" "\" ) ) )
Related
I have a bunch of files:
CAR_003.dat
CAR_003.obj
CAR_004_prev0.png
CAR_004_prev1.png
CAR_004_tex0.tga
I need to rename them to:
CAR_002.dat
CAR_002.obj
CAR_003_prev0.png
CAR_003_prev1.png
CAR_003_tex0.tga
how I can do this with cmd on windows in a batch?
You need to execute the following batch in the directory you want.
It will rename everything in the tree.
#ECHO off
SETLOCAL EnableDelayedExpansion
FOR /R %%f in (CAR*) DO (
FOR /F "usebackq tokens=1,2,* delims=_" %%m in ('%%~nxf') do (
SET filePath=%%~dpf
SET filePrefix=%%m_
SET /a fileNumber=1%%~nn-1001
SET fileNumber=000!fileNumber!
SET fileNumber=!fileNumber:~-3!
SET filePosfix=%%~no
SET fileExt=%%~xf
IF [!filePosfix!] EQU [] (
SET fileRest=%%~xf
) ELSE (
SET fileRest=_!filePosfix!!fileExt!
)
REM ECHO %%f
REM ECHO !filePath!!filePrefix!!fileNumber!!fileRest!
REM ECHO ~~~~~~~
MOVE "%%f" "!filePath!!filePrefix!!fileNumber!!fileRest!"
)
)
I am a newbie to Windows Scripting.
I am trying to list some txt files in several sub directories & want to copy a user selected file to a new destination. Please note that the file name is unique in different locations.
I got the first part to work (Listing out the files & locations) using the following script, but I am unable to copy the selected file to the new location.
#ECHO OFF
SET index=1
SETLOCAL ENABLEDELAYEDEXPANSION
SET FFPath="C:\Scripts - Backup Server\DKXpress_bkp"
SET NewPath=C:\DKServer
ECHO Recursively searching %FFPath%
echo.
FOR /F "delims=" %%f in ('DIR %FFPath%\*.txt /a:-d /s /b') DO (
SET file!index!=%%f
ECHO !index! - %%f
SET /A index=!index!+1
)
SETLOCAL DISABLEDELAYEDEXPANSION
SET /P selection="select file by number:"
SET file%selection% >nul 2>&1
IF ERRORLEVEL 1 (
ECHO invalid number selected
EXIT /B 1
)
SET NewFile=file%selection%
ECHO Copying %NewFile% to %NewPath%
ECHO.
COPY /Y "%NewFile%" "%NewPath%"
ECHO.
PAUSE
I think I am doing this part wrong
SET NewFile=file%selection%
Thank you all in advance
You don't need to set an index variable or delayed expansion, if you let Find do the work for you:
#Echo Off
Set "FFPath=C:\Scripts - Backup Server\DKXpress_bkp"
Set "NewPath=C:\DKServer"
Echo Recursively searching %FFPath%
Echo=
For /F "Delims==" %%A In ('"Set File[ 2>Nul"') Do Set "%%A="
For /F "Tokens=1* Delims=]" %%A In (
'"Dir /B/S/A-D-S-L "%FFPath%\*.txt" 2>Nul|Find /N /V """') Do (
Echo %%A] %%B
Set "File%%A]=%%B"
)
Echo=
Set /P "#=Select file by number: "
Echo=
For /F "Tokens=1* Delims==" %%A In ('"Set File[%#%] 2>Nul"') Do (
Echo Copying %%B to %NewPath%&Echo=
Copy /Y "%%B" "%NewPath%"
GoTo :End
)
Echo Invalid number selected
:End
Echo=
Pause
You need to use delayed expansion to get the file name assigned to the variable correctly.
SET NewFile=!file%selection%!
Remove the setlocal to disable delayed expansion.
You can try something like that :
#ECHO OFF
:Main
cls
SET index=1
SETLOCAL ENABLEDELAYEDEXPANSION
SET FFPath="C:\Scripts - Backup Server\DKXpress_bkp"
SET "NewPath=C:\DKServer"
ECHO Recursively searching %FFPath%
echo.
FOR /F "delims=" %%f in ('DIR %FFPath%\*.txt /a:-d /s /b') DO (
SET filepath[!index!]=%%f
ECHO [!index!] - %%~nxf - %%f
SET /A index=!index!+1
)
echo(
echo select file by number :
set /p Input=""
For /L %%i in (1,1,%index%) Do (
If "%INPUT%" EQU "%%i" (
ECHO Copying "!filepath[%%i]!" to "!NewPath!"
COPY /Y "!filepath[%%i]!" "!NewPath!"
)
)
echo Copying another file ? (Y = Yes or N = No) ?
set /p input2=""
If /I "!input2!"=="Y" (
goto :Main
) else (
goto :eof
)
I have successfully used a batch file which counts the total number of files and directories in a root directory.
Directory structure:
Here is the current script: (gets the number of files and folders returning subfolders up to the nth child).
#echo off
set "drive=D:\Download\app"
for /d %%r in ("%drive%\*") do (
echo Path: %%~fr
for /F "tokens=1,2,3 delims= " %%i in ('dir/a/s %%~fr ^| find /i "bytes"') do if "%%j"=="File(s)" (
set numfiles=%%i
)ELSE (
for /f %%a in ('dir /b /s /ad %%~fr ^|find /c /v "" ') do set numfolders=%%a)
echo Files: %numfiles%
echo Folds: %numfolders%
)
First the program outputs the total number of files and total number of folders in the root directory and then it goes to first subfolder and outputs the same for it's whole tree, then it moves to the next folder at that level etc.
EDIT
I have done the part where it go to 1 level of subfolders and get the total number of files and folders but I want it up to N number of subfolders which mean it should output total number for each and every folder in root directory.
Here is the extended code.
#echo off
setLocal EnableDelayedExpansion
set "drive=C:\Users\%USERNAME%\Downloads\Sandukchi"
set numfiles=
set numfolders=
set count=0;
for /d %%r in ("%drive%\*") do (
echo %%r
SET /A count=count + 1
for /d %%a in ("%%r\*") do set modifiedDate=%%~ta
for /F "tokens=1,2,3 delims= " %%i in ('dir/a/s "%%r\*" ^| find /i "File(s)"') do set fileSizeBytes=%%k
for %%* in ("%%r") do set folderName=%%~nx*
for /F "tokens=1,2,3 delims= " %%i in ('dir/a/s "%%r\*" ^| find /i "bytes"') do if "%%j"=="File(s)" (
set numfiles=%%i
)ELSE (
for /f %%a in ('dir /b /s /ad "%%r\*" ^|find /c /v "" ') do set numfolders=%%a)
echo Last Modified Date: !modifiedDate!
echo Folder Size: !fileSizeBytes! KB
echo Total Number of Files: !numfiles!
echo Total Number of Folders: !numfolders!
(
echo !count! %%r !folderName! !modifiedDate! Total Size !fileSizeBytes!KB Total Files !numfiles! Total Folder !numfolders!
echo.
)>>output.txt
)
#ECHO Off
SETLOCAL
SET "sourcedir=."
SET "tempfile=%temp%\##__##.txt"
SET "dirname="
(
FOR /f "tokens=1,2,*delims= " %%w IN (
'dir /s "%sourcedir%\*" '
) DO (
IF "%%w"=="Directory" (
SET "dirname=%sp256%%%y"&SET /a fcnt=0&SET /a dcnt=-2
) ELSE (
FOR /f "delims= " %%p IN ("%%y") DO (
IF "%%p"=="<DIR>" SET /a dcnt+=1
)
)
IF "%%x"=="File(s)" CALL ECHO %%dirname%%*%%w*%%dcnt%%
)
)>"%tempfile%"
FOR /f "tokens=1,2,*delims=*" %%a IN ('sort "%tempfile%"') DO ECHO directory %%a&ECHO files %%b&echo subdirs %%c
GOTO :EOF
You would need to change the setting of sourcedir to suit your circumstances.
Generates a tempfile. No attempt made to delete the tempfile as it may contain useful data.
Run a standard dir/s command, and pick out the lines which start directory (which indicates a new directoryname) and those where the third space-delimited token is <DIR> for counting subdirectories. When the lines with second token File(s) appears, output the name, filecount and directorycount to a tempfile.
Sort the tempfile and report.
Note: %%y contains the third token onwards from each line. This is retokenised, selecting the first token only (default) to %%p isolating the third token of the original line.
The tempfile is produced using * as a separator since * is not a valid filename character.
dcnt is set to -2 to start the count-of-directories because both . and .. are reported as directorynames in a dir /s.
Give a try for this code :
#echo off
Setlocal EnableDelayedExpansion
#For /D %%D in (*) DO (
Set "Folder=%%~D"
PUSHD "!Folder!"
FOR /F %%H in ('dir /a-d /b 2^>NUL^|find /C /V "" ') DO ( Set "numFiles=%%H" )
FOR /F %%I in ('dir /ad /b 2^>NUL^|find /C /V "" ') DO ( Set "numSubFolders=%%I" )
POPD
echo The Folder "!Folder!" has !numSubFolders! SubFolders and !numFiles! Files
)
)
pause & exit
I have about 12TB (and growing) library, distributed over 3 HDDs, of video files and I would like to back them up to an external harddrive. I am using Windows 10 Pro.
My backup drive has only 8TB and I would like to always backup the newest 8TB of video files. So far I have tried about 10 sync tools but none of them allowed me to copy files according to creation date.
Also with robocopy I haven't found a way to copy only the latest 8TB of files.
Any suggestions?
I have 2 batch scripts for you that do what you have asked for. The main difference between them is, that the 1st script is using where to locate all the files which will use the timestamp of the last change. To use another timestamp e.g. last access or time of creation you have to use the 2nd script I attached which uses dir.
1.
Batch script using where to locate files:
It takes minimum 2 arguments:
Usage: batch.bat <dst> <src_1> [<src_...> <src_n>]
It uses the where /r <src_n> * /t command which will build a list of all files in all subdirectories with a timestamp of the last change in the following format:
<size> <date> <time> <file name>
5397 11.07.2017 14:32:09 C:\Users\...\foo.txt
10860 12.07.2017 11:25:15 C:\Users\...\bar.log
The timestamp is of last change if you need the time of the creation or last access take the 2nd batch script below which is using dir as there is the possibility to choose between different timestamps.
This output will be written (without the column size) into a temporary file under the temp dir %TEMP% (will be deleted automatically after script) for every source that is passed via the argument list. The complete temporary file is sorted by the date and time, newest first.
This sorted output will be used to copy it into the destination folder.
Example:
Current directory in cmd is C:\...\Desktop):
batch.bat "backup_folder" "F:\folder" "F:\folder with space"
Current directory somewhere:
batch.bat "C:\...\Desktop\backup_folder" "F:\folder" "F:\folder with space"
The C:\...\Desktop\backup_folder will contain 2 folders folder and folder with space which contain all files of these source folders after the scripts operation.
In your case the batch script would copy only 8 TB of the newest files because then the drive will be full and the batch script will exit because it recognizes copy errors.
The batch script:
#echo off
setlocal enabledelayedexpansion
rem Check if at least 2 arguments are passed
set INVARGS=0
if [%1] == [] set INVARGS=1
if [%2] == [] set INVARGS=1
if %INVARGS% == 1 (
echo Usage: %0 ^<dst^> ^<src_1^> ^<src_...^> ^<src_n^>
goto :EOF
)
rem Store Carriage return character in CR (used for spinner function, see below)
for /f %%a in ('copy /Z "%~dpf0" nul') do set "CR=%%a"
rem Set temp file name
set "uniqueFile=%TEMP%\%0_%RANDOM%.tmp"
rem Set destination path and shift to next argument
set "dstpath=%~1"
shift
rem Store src_1 to src_n arguments into src array
set idx=0
:again
rem If %1 is blank, we are finished
if not [%1] == [] (
if not exist "%~1" (
echo The following source folder doesn't exist:
echo "%~1"!
echo The program will terminate!
goto :end
)
pushd "%~1"
set "src[%idx%]=!cd!"
if [!src[%idx%]:~-1!] == [\] (
set src[%idx%]=!src[%idx%]:~0,-1!
)
set /a idx=%idx%+1
popd
rem Shift the arguments and examine %1 again
shift
goto :again
)
rem Build command string:
rem where /r "src_1" * /t ^& where /r "src_..." * /t ^& where /r "src_n" * /t ^& break"
set "command="
for /F "tokens=2 delims==" %%s in ('set src[') do (
set "command=!command!where /r "%%s" * /t ^& "
)
set "command=!command!break"
echo "Command: ^<!command!^>"
rem Clear temp file and write files to copy in it
break>"%uniqueFile%"
for /f "tokens=2,3,4,* delims= " %%F in ('!command!') do (
call :spinner
echo %%F %%G %%H %%I>>"%uniqueFile%"
)
rem Open the built file list
echo File list will be opened...
%uniqueFile%
rem Ask user if copying should start
echo Should this files copied into %dstpath%? (Y/N)
set INPUT=
set /P INPUT=Answer?:%=%
if not [%INPUT%] == [y] (
if not [%INPUT%] == [Y] (
goto :end
)
)
set "dstpathPart="
rem Sort files newest first (last changed timestamp)
for /f "tokens=3,* delims= " %%F in ('type "%uniqueFile%" ^| sort /r') do (
rem Build destination part from source folder names
call :buildDestinationPath dstpathPart "%%F %%G"
rem Prepend the destination folder
set "dstFile=!dstpath!\!dstpathPart!"
rem Make directories that doesn't exists
for %%F in ("!dstFile!") do set "directory=%%~dpF"
if not exist "!directory!" ( mkdir "!directory!" )
rem Copy files and echo it
echo copy /y "!file!" "!dstFile!"
copy /y "!file!" "!dstFile!"
echo.
rem If copying failed exit program
if errorlevel 1 (
echo Copying failed... Maybe there is no more space on the disk!
echo The program will terminate!
goto :end
)
)
goto :end
rem Function definitions
:buildDestinationPath
for /F "tokens=2 delims==" %%s in ('set src[') do (
rem Go into folder e.g.: C:\src_1\ --> C:\
pushd "%%s"
cd ..
rem file contains full path of the where command
set "file=%~2"
rem Remove trailing space
if "!file:~-1!" == " " (
call set "file=%%file:~0,-1%%"
)
rem remove src folder from file to make it relative
rem e.g. C:\src_1\foo\bar\file1.txt --> src_1\foo\bar\file1.txt
call set "dstpathPart_temp=%%file:!cd!=%%"
rem Switch back to origin folder
popd
rem If the folder name changed the substring taken was right so take next
if not [!dstpathPart_temp!] == [!file!] (
set "%~1=!dstpathPart_temp!"
goto :next
)
)
:next
goto :EOF
:spinner
set /a "spinner=(spinner + 1) %% 4"
set "spinChars=\|/-"
<nul set /p ".=Building file list... !spinChars:~%spinner%,1!!CR!"
goto :EOF
:end
del "%uniqueFile%"
goto :EOF
2.
Batch script using dir to locate files:
It takes one more argument so that you need minimum 3 arguments:
Usage: batch.bat <timeordering> <dst> <src_1> [<src_...> <src_n>]
It will generate the same list as explained above but with the help of the dir command. The dir command takes the following parameter which is the <timeordering> parameter of the script:
/tc Creation
/ta Last access
/tw Last written
The batch script:
#echo off
setlocal enabledelayedexpansion
rem Check if at least 2 arguments are passed
set INVARGS=0
if [%1] == [] set INVARGS=1
if [%2] == [] set INVARGS=1
if [%3] == [] set INVARGS=1
if %INVARGS% == 1 (
echo Usage: %0 ^<timeordering^> ^<dst^> ^<src_1^> ^<src_...^> ^<src_n^>
goto :EOF
)
rem Store Carriage return character in CR (used for spinner function, see below)
for /f %%a in ('copy /Z "%~dpf0" nul') do set "CR=%%a"
rem Set temp file name
set "uniqueFile=%TEMP%\%0_%RANDOM%.tmp"
rem Set timeordering and destination path and shift to next argument
set "timeordering=%~1"
shift
set "dstpath=%~1"
shift
rem Store src_1 to src_n arguments into src array
set idx=0
:again
rem If %1 is blank, we are finished
if not [%1] == [] (
if not exist "%~1" (
echo The following source folder doesn't exist:
echo "%~1"!
echo The program will terminate!
goto :end
)
pushd "%~1"
set "src[%idx%]=!cd!"
if [!src[%idx%]:~-1!] == [\] (
set src[%idx%]=!src[%idx%]:~0,-1!
)
set /a idx=%idx%+1
popd
rem Shift the arguments and examine %1 again
shift
goto :again
)
rem Clear temp file and write files to copy in it
break>"%uniqueFile%"
rem call commands with all sources:
rem call :getFileInformation /TC "src_1\*"
rem /TW
rem /TA
for /F "tokens=2 delims==" %%s in ('set src[') do (
call :getFileInformation %timeordering% "%%s\*" "%uniqueFile%""
)
rem Open the built file list
echo Unsorted file list will be opened...
%uniqueFile%
rem Ask user if copying should start
echo Should this files copied into %dstpath%? (Y/N)
set INPUT=
set /P INPUT=Answer?:%=%
if not [%INPUT%] == [y] (
if not [%INPUT%] == [Y] (
goto :end
)
)
set "dstpathPart="
rem Sort files newest first (last changed timestamp)
for /f "tokens=3,* delims= " %%F in ('type "%uniqueFile%" ^| sort /r') do (
rem Build destination part from source folder names
call :buildDestinationPath dstpathPart "%%F %%G"
rem Prepend the destination folder
set "dstFile=!dstpath!\!dstpathPart!"
rem Make directories that doesn't exists
for %%F in ("!dstFile!") do set "directory=%%~dpF"
if not exist "!directory!" ( mkdir "!directory!" )
rem Copy files and echo it
echo copy /y "!file!" "!dstFile!"
copy /y "!file!" "!dstFile!"
echo.
rem If copying failed exit program
if errorlevel 1 (
echo Copying failed... Maybe there is no more space on the disk!
echo The program will terminate!
goto :end
)
)
goto :end
rem Function definitions
:buildDestinationPath
for /F "tokens=2 delims==" %%s in ('set src[') do (
rem Go into folder e.g.: C:\src_1\ --> C:\
pushd "%%s"
cd ..
rem file contains full path of the where command
set "file=%~2"
rem Remove trailing space
if "!file:~-1!" == " " (
call set "file=%%file:~0,-1%%"
)
rem remove src folder from file to make it relative
rem e.g. C:\src_1\foo\bar\file1.txt --> src_1\foo\bar\file1.txt
call set "dstpathPart_temp=%%file:!cd!=%%"
rem Switch back to origin folder
popd
rem If the folder name changed the substring taken was right so take next
if not [!dstpathPart_temp!] == [!file!] (
set "%~1=!dstpathPart_temp!"
goto :next
)
)
:next
goto :EOF
:getFileInformation
for /f "delims=" %%a in ('dir /s /b /a-d %~1 "%~2"') do (
for /f "tokens=1,2 delims= " %%b in ('dir %~1 "%%a" ^| findstr /l /c:"%%~nxa"') do (
echo %%b %%c %%a>>"%~3"
call :spinner
)
)
goto :EOF
:spinner
set /a "spinner=(spinner + 1) %% 4"
set "spinChars=\|/-"
<nul set /p ".=Building file list... !spinChars:~%spinner%,1!!CR!"
goto :EOF
:end
del "%uniqueFile%"
goto :EOF
I have a folder with many .txt files. I would like to find string "X" in all of these files then I would like to copy the found strings into .txt files into a different folder.
So far I have tried :
#echo on
findstr /m "X" "%userprofile%\Desktop\New_Folder\New_Folder\*.txt"
if %errorlevel%==0 do (
for %%c in (*.txt) do (
type %%c >> "%UserProfile%\Desktop\New_Folder\%%~nc.txt"
pause
I do not understand the output %%~nc.txt part it's suppost to copy the changed .txt files to a new folder with the same name.
I would like to point out that string "X" is found in different places in the .txt file.
This batch file can did the trick (-_°)
So, just give a try : ScanfilesWordSearch_X.bat
#ECHO OFF
::******************************************************************************************
Title Scan a folder and store all files names in an array variables
SET "ROOT=%userprofile%\Desktop"
Set "NewFolder2Copy=%userprofile%\Desktop\NewCopyTxtFiles"
SET "EXT=txt"
SET "Count=0"
Set "LogFile=%~dp0%~n0.txt"
set "Word2Search=X"
SETLOCAL enabledelayedexpansion
REM Iterates throw the files on this current folder and its subfolders.
REM And Populate the array with existent files in this folder and its subfolders
For %%a in (%EXT%) Do (
Call :Scanning "%Word2Search%" "*.%%a"
FOR /f "delims=" %%f IN ('dir /b /s "%ROOT%\*.%%a"') DO (
( find /I "%Word2Search%" "%%f" >nul 2>&1 ) && (
SET /a "Count+=1"
set "list[!Count!]=%%~nxf"
set "listpath[!Count!]=%%~dpFf"
)
) || (
( Call :Scanning "%Word2Search%" "%%~nxf")
)
)
::***************************************************************
:Display_Results
cls & color 0B
echo wscript.echo Len("%ROOT%"^) + 20 >"%tmp%\length.vbs"
for /f %%a in ('Cscript /nologo "%tmp%\length.vbs"') do ( set "cols=%%a")
If %cols% LSS 50 set /a cols=%cols% + 20
set /a lines=%Count% + 10
Mode con cols=%cols% lines=%lines%
ECHO **********************************************************
ECHO Folder:"%ROOT%"
ECHO **********************************************************
If Exist "%LogFile%" Del "%LogFile%"
rem Display array elements and save results into the LogFile
for /L %%i in (1,1,%Count%) do (
echo [%%i] : !list[%%i]!
echo [%%i] : !list[%%i]! -- "!listpath[%%i]!" >> "%LogFile%"
)
(
ECHO.
ECHO Total of [%EXT%] files(s^) : %Count% file(s^) that contains the string "%Word2Search%"
)>> "%LogFile%"
ECHO(
ECHO Total of [%EXT%] files(s) : %Count% file(s)
echo(
echo Type the number of file that you want to explore
echo(
echo To save those files just hit 'S'
set /p "Input="
For /L %%i in (1,1,%Count%) Do (
If "%INPUT%" EQU "%%i" (
Call :Explorer "!listpath[%%i]!"
)
IF /I "%INPUT%"=="S" (
Call :CopyFiles
)
)
Goto:Display_Results
::**************************************************************
:Scanning <Word> <file>
mode con cols=75 lines=3
Cls & Color 0E
echo(
echo Scanning for the string "%~1" on "%~2" ...
goto :eof
::*************************************************************
:Explorer <file>
explorer.exe /e,/select,"%~1"
Goto :EOF
::*************************************************************
:MakeCopy <Source> <Target>
If Not Exist "%~2\" MD "%~2\"
Copy /Y "%~1" "%~2\"
goto :eof
::*************************************************************
:CopyFiles
cls
mode con cols=80 lines=20
for /L %%i in (1,1,%Count%) do (
echo Copying "!list[%%i]!" "%NewFolder2Copy%\"
Call :MakeCopy "!listpath[%%i]!" "%NewFolder2Copy%">nul 2>&1
)
Call :Explorer "%NewFolder2Copy%\"
Goto:Display_Results
::*************************************************************
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "mystring=x"
FOR %%a IN ("%sourcedir%\*.txt") DO FINDSTR "%mystring%" "%%a">nul&IF NOT ERRORLEVEL 1 FINDSTR "%mystring%" "%%a">"%destdir%\%%~nxa"
GOTO :EOF
You would need to change the settings of sourcedir and destdir to suit your circumstances and set mystring appropriately, noting that you may have to adjust the findstr switches to accomodate case, literal and space-in-target-string.
Naturally, you could code sourcedir etc. directly as literals, but doing it this way means that the relevant strings need only be changed in one place.
You are close, but checking the ErrorLevel of findstr does not make sense here as this reflects the overall result, that is, ErrorLevel is set to 0 in case any of the files contain the search string.
I would parse the output of findstr /M using a for /F loop and copy the returned files in the body:
for /F "eol=| delims=" %%F in ('
findstr /M /I /C:"X" "%USERPROFILE%\Desktop\New_Folder\New_Folder\*.txt"
') do (
copy "%%F" "%USERPROFILE%\Desktop\New_Folder\"
)
This copies all those files which contain the literal search string (in a case-insensitive manner).