cmd line rename file with date and time - date

Project moving forwards, I can see why creating .bat files to do things can become addictive!
I can now save somefile.txt at regular intervals, I then rename somefile.txt by adding the time and date to create a unique file name
ren somefile.txt somefile_%time:~0,2%%time:~3,2%-%date:~-10,2%%date:~3,2%%date:~-4,4%.txt
As an example, the code above has just renamed somefile.txt to somefile_1317_13022011.txt (1317hrs on 13th February 2011)
I ran
ren somefile.txt somefile_%time:~0,2%%time:~3,2%-%date:~-10,2%%date:~7,2%%date:~-4,4%.txt
yesterday, it ran successfully until midnight, and then it crashed (syntax error) although it was saving as 12012011 for the date (12th Jan 2011) instead of the correct date of 12022011.
Will the current version ran past midnight? Am I confusing myself with UK vs US date format?

Animuson gives a decent way to do it, but no help on understanding it. I kept looking and came across a forum thread with this commands:
Echo Off
IF Not EXIST n:\dbfs\doekasp.txt GOTO DoNothing
copy n:\dbfs\doekasp.txt n:\history\doekasp.txt
Rem rename command is done twice (2) to allow for 1 or 2 digit hour,
Rem If before 10am (1digit) hour Rename starting at location (0) for (2) chars,
Rem will error out, as location (0) will have a space
Rem and space is invalid character for file name,
Rem so second remame will be used.
Rem
Rem if equal 10am or later (2 digit hour) then first remame will work and second will not
Rem as doekasp.txt will not be found (remamed)
ren n:\history\doekasp.txt doekasp-%date:~4,2%-%date:~7,2%-%date:~10,4%_#_%time:~0,2%h%time:~3,2%m%time:~6,2%s%.txt
ren n:\history\doekasp.txt doekasp-%date:~4,2%-%date:~7,2%-%date:~10,4%_#_%time:~1,1%h%time:~3,2%m%time:~6,2%s%.txt
I always name year first YYYYMMDD, but wanted to add time. Here you will see that he has given a reason why 0,2 will not work and 1,1 will, because (space) is an invalid character. This opened my eyes to the issue. Also, by default you're in 24hr mode.
I ended up with:
ren Logs.txt Logs-%date:~10,4%%date:~7,2%%date:~4,2%_%time:~0,2%%time:~3,2%.txt
ren Logs.txt Logs-%date:~10,4%%date:~7,2%%date:~4,2%_%time:~1,1%%time:~3,2%.txt
Output:
Logs-20121707_1019

Digging up the old thread because all solutions have missed the simplest fix...
It is failing because the substitution of the time variable results in a space in the filename, meaning it treats the last part of the filename as a parameter into the command.
The simplest solution is to just surround the desired filename in quotes "filename".
Then you can have any date pattern you want (with the exception of those illegal characters such as /,\,...)
I would suggest reverse date order YYYYMMDD-HHMM:
ren "somefile.txt" "somefile-%date:~10,4%%date:~7,2%%date:~4,2%-%time:~0,2%%time:~3,2%.txt"

following should be your right solution
ren somefile.txt somefile_%time:~0,2%%time:~3,2%-%DATE:/=%.txt

I took the above but had to add one more piece because it was putting a space after the hour which gave a syntax error with the rename command.
I used:
set HR=%time:~0,2%
set HR=%Hr: =0%
set HR=%HR: =%
rename c:\ops\logs\copyinvoices.log copyinvoices_results_%date:~10,4%-%date:~4,2%-%date:~7,2%_%HR%%time:~3,2%.log
This gave me my format I needed:
copyinvoices_results_2013-09-13_0845.log

problem in %time:~0,2% can't set to 24 hrs format, ended with space(1-9), instead of 0(1-9)
go around with:
set HR=%time:~0,2%
set HR=%Hr: =0% (replace space with 0 if any <has a space in between : =0>)
then replace %time:~0,2% with %HR%
good luck

ls | xargs -I % mv % %_`date +%d%b%Y`
One line is enough.
ls all files/dirs under current dir and append date to each file.

I tried to do the same:
<fileName>.<ext> --> <fileName>_<date>_<time>.<ext>
I found that :
rename 's/(\w+)(\.\w+)/$1'$(date +"%Y%m%d_%H%M%S)'$2/' *

Related

How to append file's last modification date to file name on moving the file?

I have an Excel add-in for my organization that I regularly update. I have a batch file which moves the previous add-in to an "old" directory, and I want to append the file's last modified date to the file name in order to keep track of all previous versions.
Using %DATE% I can append the current date to the filename, but I want to know how I can append the date for when the file was last modified.
This is my batch file so far, using the %DATE% command.
Ren J:\40_MS\435_Milj›\Annet\Datah†ndtering\Add-ins\435_Milj›.xlam 435_Milj›_old.xlam
Move J:\40_MS\435_Milj›\Annet\Datah†ndtering\Add-ins\435_Milj›_old.xlam J:\40_MS\435_Milj›\Annet\Datah†ndtering\Add-ins\Old\
Ren J:\40_MS\435_Milj›\Annet\Datah†ndtering\Add-ins\Old\435_Milj›_old.xlam 435_Milj›_%DATE%.xlam
Any suggestions are greatly appreciated.
The suggested duplicate doesn't actually explain how to append the file date to the file name. I tried using this script:
Ren C:\Temp\435_Milj›.xlam 435_Milj›_old.xlam
Move C:\Temp\435_Milj›_old.xlam C:\Temp\Old\
for %a in (C:\Temp\Old\435_Milj›_old.xlam) do set MyFileDate=%~ta
Ren C:\Temp\Old\435_Milj›_old 435_Milj›_%MyFileDate%.xlam
But it didn't work. What am I doing wrong?

How do I find last Sunday's date and save it in a variable in a Windows batch file

I have a script that needs to connect to an ftp server and download a file that is only created on Sunday and Sunday's yyyy-mm-dd-hh-mm-ss is appended to the file name. I need to find the last Sunday's date (based on today's date, I assume) and convert it to yyyy-mm-dd (I don't care about the time) so I can construct the filename in my ftp script. I have searched a lot of threads on this and other sites, but I'm kind of a novice at batch syntax. I cannot make assumptions about the date format on the machine that will run this script, but it will be in the same timezone as the ftp server and it will be running at least Windows 7. I thought about using the PowerShell solution in HOW to find last SUNDAY DATE through batch but I've read there are issues with PS script portability. Any help is greatly appreciated. Let me know if I need to provide more detail. Thanks!
(Get-Date).AddDays(-(get-date).dayofWeek.value__)
A couple years ago I wrote a batch script to find yesterday's date. I made it able to calculate 'yesterday' based on today's date. It takes into account months ending on the 30th or 31st, and even the next few leap years. The way I wrote it expects the date to be in the format 'Wed 02/24/2016' or 'ddd MM/DD/YYYY', so it may not be useful to you.
As I look at it now, it's probably more complicated than it needs to be and could probably use some cleanup, but it worked for my purposes. You might be able to modify it somehow to make it find last Sunday, instead of yesterday.
set yearCounter=0
set yyyy=%date:~10,4%
set mm=%date:~4,2%
set dd=%date:~7,2%
::use these to override the actual date values for testing
::set yyyy=xxxx
::set mm=xx
::set dd=xx
if %dd%==01 goto LDoM ::Last Day of Month
set DS=%yyyy%%mm%%dd%
set /A yesterday=%DS%-1
goto endyesterday
:LDoM
set /A lastyyyy=%yyyy%-%yearCounter%
if %yesterday:~4,2%==01 set lastmm=12& set lastdd=31& goto LDoY ::Last Day of Year
if %yesterday:~4,2%==02 set lastmm=01& set lastdd=31
if %yesterday:~4,2%==03 set lastmm=02& goto february
if %yesterday:~4,2%==04 set lastmm=03& set lastdd=31
if %yesterday:~4,2%==05 set lastmm=04& set lastdd=30
if %yesterday:~4,2%==06 set lastmm=05& set lastdd=31
if %yesterday:~4,2%==07 set lastmm=06& set lastdd=30
if %yesterday:~4,2%==08 set lastmm=07& set lastdd=31
if %yesterday:~4,2%==09 set lastmm=08& set lastdd=31
if %yesterday:~4,2%==10 set lastmm=09& set lastdd=30
if %yesterday:~4,2%==11 set lastmm=10& set lastdd=31
if %yesterday:~4,2%==12 set lastmm=11& set lastdd=30
set yesterday=%lastyyyy%%lastmm%%lastdd%
goto endYesterday
:february
set leapyear=n
set lastdd=28
if %yesterday:~0,4%==2016 set leapyear=y
if %yesterday:~0,4%==2020 set leapyear=y
if %yesterday:~0,4%==2024 set leapyear=y
if %yesterday:~0,4%==2028 set leapyear=y
if %leapyear%==y set lastdd=29
set yesterday=%lastyyyy%%lastmm%%lastdd%
goto endYesterday
:LDoY
set /A yearCounter=%yearCounter%+1
set /A lastyyyy=%yyyy%-%yearCounter%
set yesterday=%lastyyyy%%lastmm%%lastdd%
:endYesterday
#echo off
echo %yyyy% %lastyyyy%
echo %mm% %lastmm%
echo %dd% %lastdd%
echo.
echo today = %yyyy%%mm%%dd%
echo yesterday = %yesterday%
Working with date and time using pure batch can be done, but it is not very convenient.
The GetTimestamp.bat utility makes date/time computations and formatting simple within a batch context. It is pure script (hybrid JScript/batch) that runs natively on any Windows machine from XP onward. The previous link points to the most recent version. The utility was first introduced with a number of examples at http://www.dostips.com/forum/viewtopic.php?t=4847.
Full documentation is available from the command line via getTimestamp /?, or getTimestamp /?? for paged output.
With GetTimestamp, the solution can be as simple as:
#echo off
:: Get the current day of the week, with 0=Sunday, 6=Saturday
:: to be used as an offset from today to get the most recent Sunday
call getTimeStamp -f {w} -r offset
:: Use the offset to get the most recent Sunday in YYYY-MM-DD format
call getTimeStamp -od -%offset% -f {iso-dt} -r lastSunday
:: Show the result
echo lastSunday=%lastSunday%
Try the following from a batch file:
for /f "usebackq" %%d in (`powershell -noprofile -command "'{0:yyyy-MM-dd}' -f [DateTime]::Now.AddDays(-1 * [DateTime]::Now.DayOfWeek)"`) do set "lastSunday=%%d"
echo %lastSunday%
:: -> e.g., "2016-02-21", when run on 2016-02-25
To try this directly on the command prompt, replace %%d with %d.
The PowerShell expression at the heart of the command,
[DateTime]::Now.AddDays(-1 * [DateTime]::Now.DayOfWeek),
which calculates the date of the most recent Sunday, was gratefully borrowed from the answer that you link to in your question.
'{0:yyyy-MM-dd}' -f ... applies the desired yyyy-mm-dd formatting to the date.
powershell -noprofile command ... invokes the PowerShell expression and outputs its result to stdout.
for /f "usebackq" %%d in (`...`) do set lastSunday=%%d captures the output from the PowerShell command and assigns it to batch variable lastSunday.
While invoking PowerShell for just one command from a batch file will be slow, being able to calculate the desired date so conveniently probably outweighs performance concerns.

Batch Script For File Date/Time

I know there are similar questions but I have not been able to make any work. I need to check a particular file date and time against the current date and time.
So far I have
Set cdate=%date%
Set filename="c:\myfile"
If Not Exist %filename% GOTO CREATEFILE
For %%f In(%filename%) DoSet filedatetime=%%~tf
If %filedatetime:~0,-9%" == "%cdate% GOTO SHOFILE
My problem is that the cdate returned has the day of the week included in the date but the file date does not. Example cdate= Thur 1/01/2015. How can I get the cdate not to have the day of the week?
Thanks
For %%f In (%filename%) Do Set "filedatetime=%%~tf"
If "%filedatetime:~0,-9%"=="%cdate:~4%" GOTO SHOFILE
Note the required space after in and do
The set "var=value" syntax ensures that any trailing spaces on the batch line are not included in the value assigned to var.
if /i "%var%"=="value" performs a comparison on variables/values containing separators (eg spaces) The '/i' make the comparison case-insensitive if required.
Your cdate can be set like this:
SET cdate=%date:~4%
This has the following output:
echo %cdate%
01/01/2015

batch rename files keeping substring and adding mm and yy

I have a series of files that have long filenames. For each filename that contains a hyphen I would like to keep the substring in position 6-8, append the _FM07_FY14.prn to the name and ignore the rest of the original filename. The new extension is now .prn. The two digits 07 stands for the month and 14 is the year. The month and year can be found from the "date created" property. Will appreciate it if you can show me how to automatically capture this mm and yy from the date created. Hardcoding this part is okay too since I can sort files by created dates and put them in separate folders.
For example
aaaaaD07.dfdd-1234.A.b.1233 new filename will be D07_FM01_FY14.prn
bbcbaA30dls-d343.a.123d new filename will be A30_FM01_FY14.prn
cdq0dG12ir3-438d.dfd.txt new filename will be G12_FM01_FY14.prn
This is the .bat file I come up with after reading many posts on here, and I don't know how to extract the mm and yy so I hard code it. I am not familiar with Powershell. I can only handle a .bat or .cmd file and run it at the command prompt. Any and all help will be highly appreciated. Thanks!
#ECHO OFF
SETLOCAL
for %%F in (*.*) do (
SET "name=%%a"
set "var=_FM01_FY14.prn"
ren *-* "%name:~6,8%var%"
)
*endlocal*
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcedir=U:\sourcedir\one"
PUSHD %sourcedir%
FOR /f "delims=" %%a IN (
'dir /b /a-d "*" '
) DO (
SET name=%%a
SET fdate=%%~ta
ECHO(REN "%%a" "!name:~5,3!_FM!fdate:~3,2!_FY!fdate:~8,2!.prn"
)
popd
GOTO :EOF
You would need to change the setting of sourcedir to suit your circumstances.
The format that I use for date is dd/mm/yyyy If yours is different, then you'll need to change the offset in the !fdate:~m,2! phrases. The value of m is the offset into the date string from the first character (the second parameter is the number of characters to select.)
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.

Script to batch rename to retain only some characters of original filename?

I need to rename thousands of rar files with original filenames of variable sizes. I must make them 10 characters long by keeping the first 3 and the last 4 characters of the original filename and adding in the middle 3 random characters [numbers].
Example:
input:
"John Doe - Jane Doe - 19073275.rar"
"XXXX - XYXY- 98705674.rar
output:
"Joh1273275.rar"
"XXX9795674.rar"
Next, the .bat should generate a .txt with the original name and the modified one underneath for each file!
I know it's possible but I'm completely stupid when it comes to writing it. Please help!
The Batch file below do what you want:
#echo off
setlocal EnableDelayedExpansion
for %%a in (*.rar) do (
set name=%%~Na
set num=00!random!
set newName=!name:~0,3!!num:~-3!!name:~-4!
ren "%%a" "!newName!%%~Xa"
echo "%%a" modified to "!newName!%%~Xa" >> log.txt
)
I'd write a script to generate the names in any simple way (say first 6 + last 4), and then check for any duplicates to be cleaned up by hand (or a second pass shifting the middle, or ...). Unless this is a repetitive job (do it daily), it isn't worth fully automatizing.