Move a single file by extension with a batch file - batch-file

this is my very first post on this site but as I already found much help on stackoverflow, I now ask this question myself. I did not find an answer to this issue. My English isn't that good and as my Problem is quite complex, I hope you guys are all able to understand me. If not or if there are any questions that are needed to be able to help me, feel free to ask.
So I want to make a Batch file that moves files by the Extension (in my case, it's .pdf) but not all of them. I know there is this command:
move "Y:\Scan\*.pdf" "Y:\Scan\Archive\"
But this will move all pdf files to the Archive Folder and I don't want that.
To get a better overview what my plan is, a small description is needed I guess.
Imagine you have a home Server and your Computer is connected to it, a Printer and a scanner aswell. I have many documents in Folders in my home Office and I want to have them all on my Server. This is done trough scanning all Sheets of paper in These Folders. Everytime I scan something, this is saved as .pdf in a Folder on my local Computer, sorted by time and Looks like this: 2017-06-15-10-30.pdf
My current script is asking 3 times for userinput. One time for a village Name, one time for a street's Name and one time for the number of the house because the Folders for the Archive should be named like the corresponding house they are referring to. So I have These 3 Inputs in my Batch already and also the whole Folder Name saved in a new variable.
My plan is to now ask the user how many pdf's are corresponding to the last created Folder and whatever the user is typing, this amount of files will be stored in that Folder. To understand this a Little better, here is what i've done so far (my Batch code).
#echo off
cls
title Archive-Script (by Relentless)
color 0b
:reset
cls
REM This is the village's name
SET ON=""
REM This is the street's name
SET SN=""
REM This is the number of the house
SET HN=""
REM This is a variable to store whether the user wants to reset the variables or not (used later)
SET RESET=""
:start
cls
IF %RESET% == N echo To overwrite the village's name, please enter the name again and hit enter. If you don't want to overwrite the name, just hit enter!
IF NOT %RESET% == N echo Please enter the village's name (confirm by pressing enter):
IF %RESET% == N echo Current name: %ON%
set /p "ON="
echo The village's name was set to %ON%!
echo.
IF %RESET% == N echo To overwrite the street's name, please enter the name again and hit enter. If you don't want to overwrite the name, just hit enter!
IF NOT %RESET% == N echo Please enter the street's name (confirm by pressing enter):
IF %RESET% == N echo Current name: %SN%
set /p "SN="
echo The street's name was set to %SN%!
echo.
IF %RESET% == N echo To overwrite the house's number, please enter the number again and hit enter. If you don't want to overwrite the number, just hit enter!
IF NOT %RESET% == N echo Please enter the house's number (confirm by pressing enter):
IF %RESET% == N echo Current number: %HN%
set /p "HN="
echo The house's number was set to %HN%!
echo.
echo.
echo.
echo.
echo.
SET FOLDERNAME="%ON%, %SN% %HN%"
echo The folder %FOLDERNAME% will now be created!
mkdir ""%FOLDERNAME%""
timeout /t 2 /nobreak
:pdfmove
cls
echo How many pdf-files are corresponding to the latest created folder?
set /p "PDF="
for /l %%x in (1,1,%PDF%) do (
echo %%x
move Y:\Scan\*.pdf Y:\Scan\%FOLDERNAME%\
)
:resetoption
cls
echo %ON%
echo %SN%
echo %HN%
echo.
echo Should the variables be resetted again? (J/N)
set /p "RESET="
IF %RESET% == J goto reset
IF %RESET% == N goto start
As you can see, I already tried to implement the move Option, but this will move ALL pdf files instead of one on each for Loop. Can anyone help me with that? I guess the code is pretty simple to understand.
Greetz Relentless

for /l %%x in (1,1,%PDF%) do (
set "moved="
for /f "delims=" %%a in ('dir /b /a-d "y:\scan\*.pdf" '
) do if not defined moved (
echo %%x : %%a
set "moved=Y"
move "Y:\Scan\%%a" Y:\Scan\%FOLDERNAME%\
)
)
I believe what you want to do is to move a user-input number of pdfs.
The above change will, for each %%x, first set the flag moved to nothing, then perform a directory-scan, in /b basic form (filename only) /a-d with no directorynames. Each of the filenames present in the directory will be assigned to %%a in turn. The delims= option allows filenames that contain spaces to be processed.
When the first file is found, its name is echoed with the sequence number and the flag is set to Y (any non-empty string will do). The file is then moved.
When the for...%%a... processes the next filename, moved is now set to a value, so no more file-moves are performed.
The entire process is then repeated for each value of %%x, so %PDF% moves of the first .pdf filename found in the source directory will be moved because one is moved each time and the dir command will not find the file that was last moved because well - it's been moved and hence is no longer in the source directory.
OK, here's a fix to produce a variable number of spaces
SET "tspaces=T"
:addspace
SET "tspaces=%tspaces% "
CALL SET "testspace=%%tspaces:~%pdf%%%"
IF "%testspace%" neq " " GOTO addspace
FOR /L %%x IN (1,1,%pdf%) DO (
set "moved="
for /f "delims=" %%a in ('dir /b /a-d "y:\scan\*.pdf" '
) do if not defined moved (
echo %%x : %%a
set "moved=Y"
call move "Y:\Scan\%%a" "Y:\Scan\%FOLDERNAME%\olddocumen%%tspaces:~0,%%x%%.pdf"
)
)
The first part sets up tspaces to t+a sufficient number of spaces.
Note that in the second part, the move is now called which resolves the variable-substring. Since %%x varies from 1 to %pdf% then the selection from tspaces is %%x characters - it has a minimum of 1, when the final character of olddocument is required; thereafter a number of spaces follow, so the t is the initial value of tspaces.

Related

batch-file - creating a file with file extension

I am a student and new here in Stack Overflow.
I am currently creating a project for my Operating System class. One of the menu would be this: The user can create, rename and delete a certain file anywhere in the directory. I already know how to rename and delete a file but I had a hard time finding the right command to create a file wherein the user can determine what file extension that certain file would be.
It is sort of like this:
//this is to show the user what available drives the computer has
echo Here are the available drives:
echo.
wmic logicaldisk get name
echo.
echo.
set /p ch2=Which drive do you want to access?
for /f "skip=1 delims=" %%x in ('wmic logicaldisk get caption') do #echo %%x >>drive%%x.txt
if exist D:\drive!ch2! (
goto specificview
)
else (
goto Invalid
)
//here the chosen drive will be viewed with its saved files and the user is asked what to do next
:specificview
cls
set ch3=
dir !ch2!:\ /w /a
pause
echo.
echo.
echo What do you want to do in this directory?
echo ================================================================
echo Press [X] to go back to choose directory
echo Press [w] to Exit
echo Press [C] to create File
echo If none of the choices, type down the name of the directory file
echo NOTE: Just press [1] to go back to the main MENU
echo ================================================================
//let's say the user will choose C to create file
set /p ch3= Please Choose:
if /i !ch3!==c (
set /p crt=Input the name of the filename:
set /p ext=Input the desired extension:
Now, I don't know what command I should use in order to complete the code. I would like to ask your help so that I can finish my project.
Thanks a lot in advance.
Not really comment, not really answer so I will make it CW!
As this question is not really a duplicate I will add a few things to change it to your needs.
I assume that your file is going to be empty and not using some special formatting or encoding.
As already visible in the answers to above question, there are a lot of ways to do that. I would suggest the answer with the most upvotes that copies NUL to a new file making it empty.
The copy command as you can see is quite simply structured: copy firstFile.something secondFile.somethingElse or in this case copy NUL fileName.ext
So in your case you would go ahead and add the following line:
copy NUL !crt!.!ext!

Windows Batch file - Delete with Y/N prompt and not allow wild cards

I don't think this is a duplicate question (much to my surprise). I'm not a fan of using batch files and I can count on 1 hand the number of times I've had to create one.
I'm trying to create a batch file for deleting 1 file at a time, without wild cards. If the file name doesn't exist, then the batch file should terminate.
My errant batch file:
#echo off
set /p image="Enter file name (e.g. car.jpg):"
set fullFileName=C:\testimages\%image%
IF EXIST "%fullFileName%" (
ECHO[
del /P /F "%fullFileName%"
) ELSE (
ECHO File %fullFileName% doesn't exist
)
pause
Correct:
Enter file name (e.g. car.jpg):car.jpg
C:\testimages\car.jpg, Delete (Y/N)?
Correct:
Enter file name (e.g. car.jpg):plane.jpg
File C:\testimages\plane.jpg doesn't exist
Press any key to continue . . .
I want to disallow any wild cards. Such as the following:
Enter file name (e.g. car.jpg):*
C:\testimages\bus.jpg, Delete (Y/N)? n
C:\testimages\car.jpg, Delete (Y/N)? n
C:\testimages\truck.jpg, Delete (Y/N)? n
Press any key to continue . . .
I am assuming you want to disallow the user entering in * or ?. There are other undocumented wildcards as well though.
#echo on
:loop
cls
set /p "image=Enter file name (e.g. car.jpg):"
(echo "%image%"|findstr /L "* ? < > ^" >nul 2>&1) && GOTO :EOF
set "fullFileName=C:\testimages\%image%"
IF EXIST "%fullFileName%" (
ECHO[
ECHO del /P /F "%fullFileName%"
) ELSE (
ECHO File "%fullFileName%" doesn't exist
)
endlocal
pause
There are probably more robust ways to check for input validation. I am sure this could be broken in some form.
Here is an option using the for /F command:
set "image=" & set /P image="Enter file name: "
for /F tokens^=1*^ delims^=?*^<^>^" %%A in ("_%image%_") do set "TEST=%%B"
if defined TEST echo There are wild-cards!
If at least one wild-card is present in %image%, %%B and hence TEST are not empty. The _ characters are prepended and appended for the approach not to fail in case wild-cards are only present at the beginning and/or at the end of %image%.
This is another option using a standard for loop:
set "image=" & set /P image="Enter file name: " & set "FLAG=#"
for %%A in ("%image%") do if /I "%image%"=="%%~nxA" (set "FLAG=") else goto :QUIT
:QUIT
if defined FLAG echo There are wild-cards!
If at least one wild-card is present in %image%, the for loop resolves it by accessing the file system and returning the matching items (zero or more); this means that the original string %image% does not equal any of the iterated items, so the if query fails; the goto is there to avoid any more iterations, hence to break the loop; if no items match, the loop does not iterate at all. If no wild-cards are present in %image%, the for loop iterates once only over the original string, hence the if condition is fulfilled and variable FLAG is cleared.

How do I save variables from a batch file then load them to use them?

I'm a pretty inexperienced coder and I love batch because its one of the more straight forward coding languages but I want to save multiple variables to a txt file or other format then "load" those same variables to the batch file not to type so the player can see but so that I can use it
This is what I have so far for loading:
:nick
cls
color 02
set /p nick= Enter your nickname:
if exist ((savegame%nick%.txt) goto load)
goto instructions
:load
for /f "blevel=" %%a in (savegame%nick%.txt) do set blevel=%%a&goto loadexist
for /f "mlevel=" %%a in (savegame%nick%.txt) do set mlevel=%%a&goto loadexist
for /f "alevel=" %%a in (savegame%nick%.txt) do set alevel=%%a&goto loadexist
this is what I have for saving:
:save
cls
echo Saving please wait...
(echo blevel=%blevel%)> savegame%nick%.txt
(echo mlevel=%mlevel%)>> savegame%nick%.txt
(echo alevel=%alevel%)>> savegame%nick%.txt
timeout /t 5 /nobreak >nul
exit
Like I said I'm very inexperienced and my goal is to create a game please feel free to point out any flaws. In my game I have 3 characters Brutus, Mediana, and Achilles. blevel, mlevel, and alevel refers to the place in the game where you are and the character you chose to play as so you don't have to play the whole game to get to where you were.
As this is obviously still a work in progress I only have one instance where you can save and its in the first Brutus promt:
:brutus 1
set blevel=1
cls
echo.
echo.
echo.
echo You chose brutus good choice but are you sure this is who you want?
echo 1) go back and choose
echo 2) continue
echo 0) save
set /p c=C:\
if "%c%" == 1 goto choose character
if "%c%" == 2 goto brutus 2
if "%c%" == 0 goto save
goto brutus 1
So when you get to a choice like this your respective level goes up. Every time I reopen the game it either closes cmd when I type the nickname I used to save the file or it doesn't work and skips over it like the file or the variables in it don't exist. My intention is to do this with all three characters at every crucial choice so in the end I will probably have at least 100 per character.
your "save" logic is ok.
For loading, you need just a single line:
for /f "delims=" %%i in (savegame%nick%.txt) do set "%%i"
When you run it with echo on, you see that it processes every line and sets your variables.

creating a batch file to copy pictures to a network drive

How do I create a batch file that will copy files from a camera to a directory that is prompted from the command line?
example folder structure: {shared drive start folder} <year> <month> <(prompt user for name)> [delete pictures after copied]
I am looking to get this to work to copy pictures from various cameras to one shared folder and have it all sorted by year then month and finally by the user prompted name. I know very little command line commands, all the switches and %'s.. i get lost pretty quickly.
Windows 7 computers and most likely SD cards in readers because most of the cameras don't show up with drive letters (this is part of my problem)
The code:
Show errors:
ECHO ON
type of file:
SET type=jpg
to set where the files are going:
NET USE M:\public\am_class\
to get user input i would use "SET /P" so i would do:
SET /P SDdrive=Enter Sd Card drive letter:
Get month and year(and day in case its needed later) to create initial folders:
FOR /F "TOKENS=1* DELIMS= "%%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS= "%%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/ "%%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ "%%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%mm%%dd%%yyyy%
change dir to the correct location... this im not sure about but the "NET USE" gives me a direction to look in (figured out and placed correct code):
cd\
cd /DM:\public\am_class\"
make new folders in above main folder
mkdir "%yyyy%"
cd "%yyyy%"
mkdir "%mm%"
cd "%mm%"
!!next question is this correct to get it to create a folder from the user prompted info? (This is corrected and correct)
SET /P foldername=Please enter assignment number and press enter:
mkdir "%foldername%"
cd "%foldername%"
Go to SDdrive:
%SDdrive%
Find the Path of the files:
FOR /F "TOKENS=2 DELIMS\" %%A IN ('dir /b /s *.%type%') DO SET p1= %%A
Change folder and copy to "foldername" folder
CD"%p1%"
COPY *.* %foldername%
Delete the SDcard pics after complete:
Set /P delete=Delete SD card pictures (y/n)?
IF /I "%delete%"=="y" GOTO delY
IF /I "%delete%"=="y" GOTO delN
:delY
%SDdrive%
del /q *.*
explorer.exe \\landis.xxx\public\am_class\%foldername%\
:delN
explorer.exe \\landis.xxx\public\am_class\%foldername%\
Pause for testing only (will be removed in final version):
Pause
I hope that helps some.
Use the net use command to map the windows share to a drive like X:\ and then use
xcopy with some appropriate arguments to copy the files.
Like I said in my comment, your question is very broad with a lot of things to consider. I wrote a batch-file that I have used for years on many versions of Windows to download my pictures from SD cards. It does a good job, but it does not take into account that two different SD cards may have the same picture names on them -- even though they are different pictures. It simply skips pictures that have already been downloaded with the same filename in the destination folder.
I'm not going to write your code for you, nor do I have the time right now to help you navigate your way through learning the batch-file language, but I can at least post the two batch files that I use so that you can see some of the techniques that I used to accomplish what you're trying to do.
I created a shortcut in the SendTo folder that points to the DownloadPictures.bat so that when I insert an SD card into the card reader, I can send the images folder on the SD card to the shortcut and it downloads all of the pictures, separating them into folders based on the year/month/day they were taken. Then it opens each distinct destination folder using explorer.exe. The CMD window does not show anything during the download (i.e., nothing is echoed to the window), however, the title shows the overall progress and current image filesize (e.g., "1/300 7341254 bytes").
In order to grep the year, month and day from the file dates, I use another batch-file I wrote called SubStr.bat that lets me get a substring of the output of any DOS command and assign it to a variable. You must use Delayed Command Line Expansion for everything to work.
Please remember that this is not meant to be a solution for your question, but is simply an example that shows how to do some of what you are asking -- so that you can use it as a reference as you work on your own solution.
DownloadPictures.bat
#echo off
setlocal ENABLEDELAYEDEXPANSION
cd /d c:\
title Counting the files to download...
set _total=0
for /f "delims=" %%i in ('dir %1 /a-d /b /s') do set /a _total+=1
set _cnt=0
for /f "delims=" %%i in ('dir %1 /a-d /b /s') do (
set /a _cnt+=1
if /I "%%~xi" neq ".ctg" (
title !_cnt!/%_total%: %%i - %%~zi bytes
call substr "echo %%~ti" _date 0 n n "" sub 0 10
call substr "set _date" _year 0 n n "" end 4
call substr "set _date" _month 0 n n "" sub 6 2
call substr "set _date" _day 0 n n "" sub 9 2
set _dir=Q:\Photographs\Downloads\!_year!.!_month!.!_day!
md !_dir! > nul 2>&1
if not defined _old_dir set _old_dir=!_dir!
if "!_dir!" neq "!_old_dir!" (explorer !_dir!&set _old_dir=!_dir!)
if not exist !_dir!\%%~nxi copy %%i !_dir! > nul 2>&1
)
)
explorer !_dir!
echo All the pictures in directory %1 have been downloaded.
endlocal
SubStr.bat
#echo off
if "%7"=="" goto Help
:ExtractString
:: Remove the first and last " and convert all "" to ".
set __command_=%1
set __command_=%__command_:""="%
set __command_=%__command_:~0,-1%
set __command_=%__command_:~1%
:: Execute the command and direct the output to a unique file.
%__command_% > %TEMP%\_záfileáz_
:: Extract the specified line from the output file. (Note: You can't use 'skip'
:: with a value of '0'.) I used '«' as the delimiter because it is a character
:: that I will never encounter and this will ensure that I get the whole line
:: returned from the 'for' statement.
if "%3"=="0" (
for /f "delims=«" %%i in (%TEMP%\_záfileáz_) do if not defined _závaráz_ (set _závaráz_=%%i)
) else (
for /f "skip=%3 delims=«" %%i in (%TEMP%\_záfileáz_) do if not defined _závaráz_ (set _závaráz_=%%i)
)
if /i "%7"=="all" goto Finish
if /i "%7"=="sub" set _závaráz_=!_závaráz_:~%8,%9!
if /i "%7"=="end" set _závaráz_=!_závaráz_:~-%8!
:Finish
:: Kill spaces, quotes.
if /i "%4"=="y" set _závaráz_=%_závaráz_: =%
if /i "%5"=="y" set _závaráz_=%_závaráz_:"=%
:: Remove unwanted characters (pad the front with an unlikely string so that the
:: FOR statement will never complain because of an empty set). The %%~i notation
:: strips quotes out of the string and spaces are delimiters. This is why they
:: each (spaces and quotes) have their own parameters above...
set __remove_=%6
set __remove_=ßa¯¦¯aß %__remove_:~1%
set __remove_=%__remove_:~0,-1%
set __remove_=%__remove_:""="%
for %%i in (%__remove_%) do set _závaráz_=!_závaráz_:%%~i=!
:: Set the output variable.
set %2=!_závaráz_!
:Cleanup
set _závaráz_=
del %TEMP%\_záfileáz_
set __command_=
set __remove_=
goto TheEnd
:Help
echo.
echo SubStr
echo ================================================================================
echo.
echo Syntax:
echo.
echo SubStr ["command"] [output variable] [Lines to Skip] [Remove Spaces]
echo [Remove Quotes] [Remove Other] [action [var1] [var2]]
echo.
echo Parameters:
echo.
echo Command - The command that creates the output characters. If the
echo command includes calling another batch file, issue the
echo command by using the 'call' function
echo (e.g., "call another.bat"). When your command is passed,
echo it must be enclosed in quotes. If part of the command needs
echo to also have quotes (i.e., for long filenames), the strings
echo within the command that need to be quoted need to be double
echo quoted (e.g., "dir ""c:\win 2000\notepad.exe"" /x"). When
echo the command is executed, the initial and final quotes will
echo be stripped off and all sets of double quotes ("") will be
echo replaced with single quotes (").
echo.
echo Output Variable - The name of the variable to use (set var=copied text).
echo.
echo Lines to Skip - The number of lines before the line from which you want to
echo copy text.
echo.
echo Remove Spaces - Removes spaces out of the copied text.
echo.
echo Remove Quotes - Removes quotes from the copied text.
echo.
echo Remove Other - A string of strings that should be removed from the copied
echo text. The set of strings or characters must be enclosed in
echo a single set of double quotes. At times, some characters
echo may not be elimated (e.g., a comma) unless it too is
echo enclosed in quotes. To do this, the quotes must be doubled.
echo For example: "a b c d "","" e f h"
echo.
echo Action - Action to perform:
echo All - Copies entire string.
echo Sub - Extracts part of the string where var1 is the
echo starting position and var2 is the number of
echo characters to copy. var1 is zero based. A negative
echo value for var2 omits the specified number of
echo characters from the end of the string.
echo End - Only extracts the specified number of characters
echo from the end of the string (specified by var1).
echo.
echo Example:
echo.
echo SubStr "dir c:\windows\system32\notepad.exe /-c" _filesize 5 y n "" sub 20 18
echo.
echo This command assigns the size of notepad.exe to the variable _filesize.
echo Try running it and then type 'set _' at the command prompt.
echo.
echo Notes:
echo.
echo Make sure delayed command line expansion is enabled in the calling batch file
echo via the "setlocal ENABLEDELAYEDEXPANSION" command, or enable it globally by
echo editing the registry as follows (and then reopen your CMD windows):
echo.
echo Location: HKEY_CURRENT_USER\Software\Microsoft\Command Processor
echo Item: DelayedExpansion
echo Type: dword
echo Value: 1
echo.
echo ================================================================================
echo.
:TheEnd
Thank you James L and User.
James:
Post 1: I though about asking some one to do it for me but then I would never learn anything from it. ignoring your telling me to the the towel in i got a working program.
Post 2: Very very useful post. Not only did it have code (i got to work no problem) you gave a description of how you used it. the first code is going to take me a while to decode what is what and how you did it. The second code it VERY HELPFUL, its well documented and i understand more of whats going on it it.
User:
This ended up being what i used to get my program to work. I had to keep it simple :)
Thank you both for your help with this posted problem.
James: thank you very much for all the code and useful information that your second post was teeming with.
This is the final working code for copying pictures from an SD card to a specific user named folder sorted by year then month then project name. This is set for the SD Drive to be drive letter "F:" you can change it to what you need or delete "#SET cameradrive=F:" and remove the "REM" from the line above and it will prompt the user for the drive letter. It takes the user input and makes it all capitals to make a cleaner looking folder. One thing to note: this doesn't work if the folder name has a space in it. I have to figure out how to fix that (ill be posting a question on it here). It then opens the folder in explorer so you can verify that everything went OK. After you have checked then you can delete the files on the SD card by pressing "y" and hitting enter. If you don't want to delete them then press "n" and hit enter. This copies EVERY PICTURE on the SD card in the nested folder so if you have multiple photos you want to go different places this wont work for you. also if your pictures aren't jpg then just change the "SET type=" to what ever your file type is. I placed a program called "USB Ejector" into the root of the SD card so that when the batch file is completed it automatically safely removes the card from windows.
# echo on
# SET type=jpg
# SET userfolder=C:
#cd /dy:\landis\public\am_class
#REM SET /P cameradrive=Enter Camera Drive Letter (ie D:) and hit Enter:
#SET cameradrive=F:
set /p foldername=Type Folder name and hit Enter:
#REM This makes everything uppercase.
# SETLOCAL ENABLEDELAYEDEXPANSION
# SET _SAMPLE="%foldername%"
# CALL :UCase _SAMPLE _RESULTS
# ECHO.%_RESULTS%
# CALL :LCase _SAMPLE _RESULTS
# ECHO.%_RESULTS%
# ENDLOCAL
# GOTO:EOF
# :LCase
# :UCase
# :: Converts to upper/lower case variable contents
# :: Syntax: CALL :UCase _VAR1 _VAR2
# :: Syntax: CALL :LCase _VAR1 _VAR2
# :: _VAR1 = Variable NAME whose VALUE is to be converted to upper/lower case
# :: _VAR2 = NAME of variable to hold the converted value
# :: Note: Use variable NAMES in the CALL, not values (pass "by reference")
# SET _UCase=A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
# SET _LCase=a b c d e f g h i j k l m n o p q r s t u v w x y z
# SET _Lib_UCase_Tmp=!%1!
# IF /I "%0"==":UCase" SET _Abet=%_UCase%
# IF /I "%0"==":LCase" SET _Abet=%_LCase%
# FOR %%Z IN (%_Abet%) DO SET _Lib_UCase_Tmp=!_Lib_UCase_Tmp:%%Z=%%Z!
# SET %2=%_Lib_UCase_Tmp%
#REM GOTO:EOF
#REM
# SET foldername=%_RESULTS%
#REM SETTING THE YEAR AND MONTH VARIABLES
# SET yyyy=%date:~10,4%
# SET mm=%date:~4,2%
#REM CREATING THE FOLDERS WITH THE NAMES AND NESTING THEM CORRECTLY
# mkdir %yyyy%
# cd %yyyy%
# mkdir "MSU Orders"
# cd "MSU Orders"
# mkdir %mm%
# cd %mm%
# mkdir "%foldername%"
# cd "%foldername%"
#REM COPY THE CONTENTS OF THE CAMREA PIC FOLDER TO THE NEW FOLDER
# xcopy /e /v %cameradrive%\DCIM\100NIKON "\\landis\public\am_class\%yyyy%\%mm%\%foldername%\"
# explorer.exe \\landis\public\am_class\%yyyy%\%mm%\%foldername%\
#REM Delete the originals prompt and then actions
# SET /P delete=Delete Original Photos from Camera (y/n)?
# IF /I %delete%==y GOTO :dely
# IF /I %delete%==n GOTO :deln
# GOTO :deln
# :dely
# cd /d%cameradrive%\DCIM\100NIKON
# del /q *.*
# GOTO :done
# :deln
# GOTO :done
# :done
# cd /dc:\
# F:\USB_Disk_Eject.exe /removethis
# pause

Add information to beginning of file using a BAT process, but keep file name convention

I am new to Stackoverflow, so I hope I am posting this in the correct area. I have been searching for an answer to my question for quite a while. I am attempting to add some information to the beginning of a file. The file that needs the information has a dynamic file name (Never the same, except for first 5 characters). You can see in my code the information I am needing in my file. The name of the file original file is LBL043629201313114512.DTA. The consist about the file name is "LB04xxxx. The XXXX is what I am searching for to make sure I grab the correct file.
I need the output to be the original file name (LBL......DTA) with the collected data at the beginning of the file. Any help would be great.
set /p STORE=Please enter store number:
set /p NAME=Please enter name:
set /p ADDRESS=Please enter address:
set /p CITY=Please enter address:
set /p STATE=Please enter State:
set /p ZIP=Please enter ZIP:
set /p SPECIAL=Add any Special Instructions:
(
echo %NAME%
echo %ADDRESS%
echo %CITY% %STATE% %ZIP%
echo %SPECIAL%
) > address.txt
copy address.txt+LBL04%STORE%*.DTA=test.txt
just append two lines at the end:
del /q LBL04%STORE%*.DTA
ren test.txt LBL04%STORE%*.DTA
Be sure, you don't need the original .DTA again (better, make a backup as long as you test your script
#ECHO OFF
SETLOCAL
FOR %%i IN (store name address
city state zip
special target) DO (SET %%i=)
set /p STORE=Please enter store number:
set /p NAME=Please enter name:
set /p ADDRESS=Please enter address:
set /p CITY=Please enter address:
set /p STATE=Please enter State:
set /p ZIP=Please enter ZIP:
set /p SPECIAL=Add any Special Instructions:
FOR %%i IN (store name address
city state zip
special) DO IF NOT DEFINED %%i (SET %%i= )
(
ECHO.%NAME%
ECHO.%ADDRESS%
ECHO.%CITY% %STATE% %ZIP%
ECHO.%SPECIAL%
) > address.txt
FOR /f %%i IN (
'dir /b /a-d /o-d lbl04%store%*.dta'
) DO IF NOT DEFINED target SET target=%%i
IF NOT DEFINED target ECHO LBL04%STORE%*.DTA NOT found&GOTO :EOF
copy address.txt+%target%=test.txt >nul
MOVE test.txt %target% >nul
type %target%
Obviously, you should try this against a copy of your real data first, not your live data.
The first FOR ensures that the variable names in the list are removed from the environment so that if they have an existing value then pressing enter at any of the prompts, that value would have been retained.
The second FOR loop ensures that each of the entered variables HAS a value. Note that target is NOT included in this group. There is a space between the = and the ).
With a simple SET instruction, SPACES are significant. The syntax (SET var=) or equivalently, SET "var=" ensures that the variable var is set to [nothing]. The problem with SET var= is that some editors leave terminal spaces on the line and under those circumstances, var will be set to those terminal spaces - and they're a little difficult to see. Also, SET var =... will set the variable "var" not the variable "var" - but that's a whole 'nother story.
Note that the ECHO statements now have a dot directly following the ECHO. The statement ECHO or ECHO will cause ECHO to report its state, and ECHO is off would appear in the output. Adding the "." gives ECHO something to chew on and it produces the line content beyond the .
The dir instruction in the next statement produces a directory list in /b basic form (filenames only) /a-d and no directory names /o-d in reverse-date order. The FOR /f is a mechanism for reading the output of the dir /b ... instruction, line-by-line. The contents of the next line of "input" read is applied to %%i each iteration. Therefore, the first filename matching LBL04%STORE%*.DTA encountered will be SET into target and since target is now set, any further lines will be ignored because of the if not defined gate.
If there were no matching files, target would not be defined (it was deleted in the very first for loop) so it's possible to produce an error message.
Otherwise, concatenate the files to test.txt and then the move statement actually replaces the file "%target% (which we know exists) with the concatenated version.
The >nul on each of these last two lines suppreses the message '1 file copied/moved`
Job done! New file TYPED as evidence

Resources