Is there any way to search for files in a directory based on date? I want to find all files with created date greater than a specific date, is it possible to do it with dir
command?
Vik David
3,6024 gold badges21 silver badges29 bronze badges
asked Feb 10, 2012 at 20:11
Karim HarazinKarim Harazin
1,4612 gold badges16 silver badges33 bronze badges
5
Just discovered the forfiles
command.
forfiles /s /m *.log /d -7 /c "cmd /c echo @path"
Will list all the log files modified more than seven days old, in all subdirectories, though it does not appear to look at the create date. It does support specifying a specific date.
See forfiles /?
for more info.
answered May 29, 2013 at 17:08
4
an easier way for me is something like
dir /s *.xlsx | find "07/14/2016"
answered Jul 14, 2016 at 20:31
skellyskelly
811 silver badge2 bronze badges
dir
by itself can not filter by date, but you can parse the output of dir
using for
command. If in your country dir
prints the date in YMD format, then you only need to compare it with given date. If the order of date parts is different, then you have to use another for
command to parse the date and change it to YMD. This will display a list of files modified after 5th Februrary.
@Echo Off
for /f "usebackq tokens=1,4 skip=5" %%A in (`dir /-c`) do (
if %%A GTR 2012-02-05 echo %%A %%B
)
if
does standard string comparison, so at the end you can get additional line if summary line passes the comparison. To avoid it, you can use if %%A GTR 2012-02-05 if exist %%B echo %%A %%B
EDIT:
There is even better approach which avoids parsing of dir
output and also allows searching by time, not only by date:
@Echo Off
for /r %%A in (*) do (
if "%%~tA" GTR "2012-02-05 00:00" echo %%~tA %%A
)
answered Feb 11, 2012 at 16:30
MBuMBu
2,8702 gold badges18 silver badges25 bronze badges
2
Well you cant as far as i know, but this sort of think will work, but still really useless unless you have a short date range
for /R %a in (01 02 03 04 05) do dir | find "02/%a/2012"
answered Feb 10, 2012 at 21:41
JustinJustin
3,2253 gold badges22 silver badges20 bronze badges
0
This is easy to do with PowerShell. I know that your question was about cmd, but PS is included in windows 7 and later. It can also be installed on XP and Vista.
Use the Get-ChildItem
command (aliased as dir
) to get all files. Pipe the output to the Where-Object
command (aliased as ?
) to return files where the date is greater then (-gt
) a specific date.
For Powershell 2.0 (default on Windows 7), you must use a scriptblock:
dir -file | ? {$_.LastWriteTimeUtc -gt ([datetime]"2013-05-01")}
For Powershell 3.0 (default on Windows and up you can use this simpler syntax instead:
dir -file | ? LastWriteTimeUtc -gt ([datetime]"2013-05-01")
The dir -file
command returns a collection of System.IO.FileInfo
objects. This file object has many properties that you can use for complex filtering (file size, creation date, etc.). See MSDN for documentation.
answered Dec 8, 2013 at 16:45
bouvierrbouvierr
3,5533 gold badges27 silver badges32 bronze badges
7
I had a similar challenge. I used forfiles
, however I noticed that it gave >= rather than just >. The input date was a variable, and so I didn’t want to go through a bunch of hoops/loops to calculate date + 1 day
(think about logic for last day of month or last day of year).
I created a function that ran forfiles
for a particular date. That gives us all files with a modification date that is >= _date_
. And for each file I check if the modification date is _date_
, and print the output to a file if and only if it is not equal. That means the output file only has entries for files that are > _date_
.
I can then check for existence of the output file to determine if any files in the current directory are greater than the input date. Moreover, if I wanted to know which files are newer, I can view the contents of the output file.
Finally, my input was parsed from a file that used a date format of MM/DD/YYYY, meaning it would be 07/01/2019 for July first. However, the date from FORFILES does not use leading zeros so I need to translate by dropping leading zeros.
My first attempt was to use /A thinking it drops the leading zeros. It doesn’t it reads the value as octal — don’t repeat the mistake of my first attempt. So I just created a little helper function :getNum that drops leading zeros.
:: ########################################################################
:: :findNewerFiles
::
:: Windowsfile interface will only tell you if a file is
:: greater than OR EQUAL to the current date. Had to figure a way
:: to get just greater than.
::
:: Use 'forfiles' to find all files that are >= the specific date, and for
:: each file if the files date is not equal to the specific date then echo
:: the file information into the new-file-log.
::
:: If the new-file-log exists after we're all done, then it means there is
:: at least one file newer than the specified date.
::
:: PARMS:
::
:: %1 - MONTH
::
:: %2 - DAY
::
:: %3 - YEAR
::
:: ERRORLEVEL:
:: 0 if no newer files found
:: !0 if a newer file was found
::
:findNewerFiles
SETLOCAL
CALL :getNum M "%~1"
CALL :getNum D "%~2"
CALL :getNum Y "%~3"
SET "RETVAL=1"
%bu.callecho% PUSHD %G[3PROOT_UNC]%
ECHO Last build date was: %M%/%D%/%Y%
del "%G[NEW_FILE_LOG]%" >nul 2>&1
FORFILES /p . /S /D +%M%/%D%/%Y% ^
/c "cmd /c if /I @ISDIR == false if not @fdate==%M%/%D%/%Y% echo @fdate @path>>%G[NEW_FILE_LOG]%"
IF EXIST "%G[NEW_FILE_LOG]%" (
SET "RETVAL=0"
TYPE "%G[NEW_FILE_LOG]%"
)
%bu.callecho% POPD
(ENDLOCAL
EXIT /B %RETVAL%)
:: ########################################################################
:: :getNum
::
:: Remove leading 0 from input number and place results in output variable
::
:: PARMS:
::
:: %1 - OUTPUT VARIABLE
:: Name of the output variable to be populated
::
:: %2 - INPUT VARIABLE
:: The number to have leading zeros trimmed from
::
:: ERRORLEVEL:
:: 0 always
::
:getNum
SETLOCAL
SET "D=%~1"
SET "M=%~2"
IF "%M:~0,1%" EQU "0" (
SET "M=%M:~1%"
)
(ENDLOCAL
SET "%D%=%M%"
EXIT /B 0)
1 / 1 / 0 Регистрация: 23.10.2011 Сообщений: 49 |
|
1 |
|
Поиск файлов по дате создания27.02.2013, 21:00. Показов 15487. Ответов 3
Здравствуйте. Есть вот такое задание Вот что я пока набросал, реализация выборки и сравнения даты: Код @echo off set data=%~T1 set mm=%data:~4,1% if %2 leq 6 echo %data% Но не знаю как в каталоге перебрать файлы чтоб сравнить их с условием
0 |
Charles Kludge Клюг 7673 / 3188 / 382 Регистрация: 03.05.2011 Сообщений: 8,380 |
||||
27.02.2013, 23:15 |
2 |
|||
Как-то так:
Ну а год допилите сами — это несложно.
0 |
Dragokas 18041 / 7644 / 891 Регистрация: 25.12.2011 Сообщений: 11,426 Записей в блоге: 17 |
||||
28.02.2013, 00:55 |
3 |
|||
Модификатор ~t, к сожалению показывает дату изменения, а не создания файла. Предлагаю dir через фильтрацию на регулярке (работает не-рекурсивно):
Добавлено через 13 минут
0 |
1 / 1 / 0 Регистрация: 23.10.2011 Сообщений: 49 |
|
06.03.2013, 15:02 [ТС] |
4 |
В общем вот такой код покатил. Код @echo off SETLOCAL ENABLEDELAYEDEXPANSION if %2 leq 6 ( for %%i in (%1/*.*) do ( set date=%%~Ti ::echo %%i set m=!date:~4,1! if %2 == !m! echo %%i ) ) else ( echo Не правильный месяц ) pause
0 |
Главным инструментом для поиска файлов служит утилита find. Она имеет множество параметров, которые позволяют задавать различные условия.
Поиск по имени файла
find ~ -name 'article.doc'
-
~
домашняя папка пользователя в качестве начального пути для поиска
-
-name
поиск по имени файла
Так же можно делать поиск по части имени
find ~ -name 'article.*'
find ~ -name '*.doc'
У параметра name есть альтернатива iname — игнорирование регистра символов.
Поиск по дате и времени
У файлов учитывается время создания (create), доступа (access) и изменения (modification). Соответственно параметры поиска начинаются с первых букв соответствующих английских слов.
find . -amin -30
Ищем файлы в текущей папке, которые открывались менее 30 минут назад.
find . -ctime -2h
Ищем файлы в текущей папке, время создания которых отличается от текущего на 2 часа.
В единицах интервала времени можно использовать модификаторы + или —, чтобы обозначить условие больше
или меньше соответственно.
Поиск по размеру
find . -size +10M
Эта команда выдаст список файлов, размер которых больше 10 мегабайт.
find . -size -10k
А эта — список файлов, размер которых меньше 10 килобайт.
Поиск по содержимому файла
Утилита find
сама не осуществляет поиск по содержимому, но ее можно использовать, чтобы задать другие граничные условия поиска. А внутри файла можно найти строку с помощью утилиты grep.
Найдем файлы в домашней папке пользователя, размер которых меньше 10 килобайт и содержащих строку «hello»
find ~ -size -10k -print0 | xargs -0 grep "hello"
-
-print0
имена файлов будет разделены символом
-
xargs
специальная утилита, которая получает из стандартного ввода набор строк и передает их в качестве аргументов следующей утилите (в нашем случае утилите grep)
-
-0
строки разделены символом
Подробнее о параметрах
Все параметры и их значения можно узнать из документации по соответствующим утилитам
- find
- grep
- xargs
Добрый день.
частично в данную тему. Есть папка, в ней разные Эксель файлы, задача скопировать самый свежий по дате обновления, скопировать в другую папку и добавить название, что бы создавалась история.
Есть рабочий сетап, но он берет верный месяц, но дату и время не учитывает, т.е. если есть файлы от 4 числа и 10, то скопирует 4 число.
Где ошибка:
@ECHO off
setlocal
CHCP 65001
SET EXT=.xlsx
SET FOLDER=G:localuserDocuments13_Warehouse_reportSlotstest
SET BACKUP_FOLDER=G:localuserDocuments13_Warehouse_reportSlots
SET DATE=%date:~6,4%%date:~3,2%%date:~0,2%_%time:~0,2%%time:~3,2%%time:~6,2%
for /F "delims=" %%A in ('DIR "%FOLDER%*%EXT%" /T:A /A:-D /B') DO SET NEW_FILE=%%~nA
copy "%FOLDER%%NEW_FILE%%EXT%" "%BACKUP_FOLDER%%NEW_FILE%_%DATE%%EXT%"