- ⏱️ Как создать каталоги или файлы с именами на текущую дату/время/месяц/год на Linux
- Создание каталогов или файлов с именами текущей даты / времени / месяца / года на Linux
- Создание каталогов или файлов с произвольным именем с текущей датой
- Создание каталогов файлов в формате ISO
- Больше примеров
- Добавить комментарий Отменить ответ
- • Свежие записи
- • Категории
- • itsecforu.ru
- • Страны посетителей
- IT is good
- Create Directories or Files Named With Current Date / Time / Month / Year
- Create Directories Or Files Named With Current Date / Time / Month / Year In Linux
- Create directories or files with custom name with current date
- Create directories of files with ISO format
- More examples
- Append date to filename in linux
- 6 Answers 6
- How To Append Current Date To Filename in Bash Shell
- Append current date to a filename
- date command FORMAT_STRING
- Bash shell append date to filename in Linux or Unix
- Shell Scripting: Create Report / Log File Names With Date in Filenames
- date Command Syntax
- Sample Shell Script
⏱️ Как создать каталоги или файлы с именами на текущую дату/время/месяц/год на Linux
Показанные далее команды создадут каталоги или файлы с именами с текущей датой или временем на основе часов вашего компьютера.
Создание каталогов или файлов с именами текущей даты / времени / месяца / года на Linux
Чтобы создать каталог и назвать его текущей датой, просто запустите:
Эта команда создаст каталог и назовет его сегодняшней датой в формате dd: mm: yyyy.
Создание каталогов или файлов с произвольным именем с текущей датой
Как насчет пользовательского имени для каталога или файла с датой / временем / месяцем / годом?
Это также возможно.
Создание каталогов файлов в формате ISO
Если вы хотите использовать формат даты ISO (например, 2020-06-06), запустите:
Все вышеперечисленные три команды дают одинаковый результат.
Для создания файлов просто замените mkdir командой «touch».
Больше примеров
Если вы хотите только день текущей даты, используйте:
Эта команда создаст каталог только с текущим днем в имени. т.е. 06.
Точно так же вы можете создавать каталоги с именем текущего месяца только в имени:
Обратите внимение что S – заглавная
Чтобы назвать каталог с текущими минутами, используйте заглавную M:
Во всех приведенных выше примерах мы создали каталоги с номерами на их именах.
Что если вы хотите назвать каталоги с фактическим названием текущего дня / месяца, например, Saturday, October и т. д.?
Добавить комментарий Отменить ответ
• Свежие записи
• Категории
• itsecforu.ru
• Страны посетителей
IT is good
Источник
Create Directories or Files Named With Current Date / Time / Month / Year
Do you know we can create directories or files named with current date, time, month, and year from command line? No? No problem. This tutorial explains how to create a directory or file with current timestamp in the name in Linux.
This will be helpful when you want to save something, for example photos, in directories named with date when they are actually taken. For example, if the photos were taken on October 16, 1984, you can create a folder named «16-10-1984».
Creating files with timestamps will make your work easier to arrange the files in order. This will also be useful when you want to automate the task using a script.
The following commands will create a directory or file and name it the current date/time/month/year based on your computer’s clock. So make sure you have setup correct time on your system.
Create Directories Or Files Named With Current Date / Time / Month / Year In Linux
To create a directory and name it the current date, simply run:
This command will create a directory and name it the today’s date in dd:mm:yyyy format.
Sample output:
Create Directories Named With Current Date, Time, Month, Year In Linux
To switch into this directory, simply replace mkdir with cd command like below.
Similarly, to create a file named with current date, time, month, year, simply replace mkdir with touch command:
Create directories or files with custom name with current date
What about a custom name for the directory or file with date/time/month/year? It is also possible.
This command will create a directory named «ostechnix.com-06-06-2020» .
Create directories or files with custom name with current date
To create a file with custom name:
Create directories of files with ISO format
If you want to use ISO date format (e.g. 2020-06-06 ) and ls will list them in date order, run:
All of the above three commands will produce the same result.
To create files, just replace mkdir with touch command.
More examples
If you want only day of the current date, use:
This command will only create the directory with current day in the name. i.e 06 .
Similarly, you can create directories with current month-only in the name:
This command will name the directories with the last two digits of current year i.e 20 . If you want the whole year (i.e. 2020 ) in the name, use Y (Uppercase Y).
How about directories name with current time? It is also possible.
This command will create a folder and name it with current time in hh:mm:ss format.
Sample output:
We can even create directories with current minutes and seconds in the name. For example, the following command will create a directory and name it with current second.
Here, S is uppercase.
To name directory with current minutes, use uppercase M :
In all of the above examples, we created the directories with numbers on their names. What if you want to name the directories with actual name of the current day/month like Sunday, October etc? It’s simple!
The above command will create a directory named «Saturday» i.e today’s name.
To create a directory with name of current month (i.e October), run:
Here is the list of supported operators that you can use to name the directories with current day, month, time, year, day of week, day of the month, time zone etc.
Источник
Append date to filename in linux
I want add the date next to a filename («somefile.txt»). For example: somefile_25-11-2009.txt or somefile_25Nov2009.txt or anything to that effect
Maybe a script will do or some command in the terminal window. I’m using Linux(Ubuntu).
Thanks in advance.
oh i almost forgot to add that the script or command should update the filename to a new date everytime you want to save the file into a specific folder but still keeping the previous files. So there would be files like this in the folder eventually: filename_18Oct2009.txt , filename_9Nov2009.txt , filename_23Nov2009.txt
6 Answers 6
You can use backticks .
There’s two problems here.
1. Get the date as a string
This is pretty easy. Just use the date command with the + option. We can use backticks to capture the value in a variable.
You can change the date format by using different % options as detailed on the date man page.
2. Split a file into name and extension.
This is a bit trickier. If we think they’ll be only one . in the filename we can use cut with . as the delimiter.
However, this won’t work with multiple . in the file name. If we’re using bash — which you probably are — we can use some bash magic that allows us to match patterns when we do variable expansion:
Putting them together we get:
And if we’re less worried about readability we do all the work on one line (with a different date format):
Источник
How To Append Current Date To Filename in Bash Shell
H ow do I append current date (mm_dd_yyyy format) to a filename (e.g., backup_mm_dd_yyyy.sql) under Linux and UNIX like operating systems? How can I append a current date from a variable to a filename under Linux or Unix bash shell? How do I append date to filename?
We use the date command to show or set the system date and time. Further we can show the current date and time in the given FORMAT. This page explains how to append current date to a filename using various command line options.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | Bash running on Linux, macOS or Unix |
Est. reading time | 4 minutes |
Append current date to a filename
To get the current date in mm_dd_yyyy format use the following date format syntax:
You can store this to a variable name:
Alternat syntax for command substitution is as follows:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Now we can append the current date stored in $now to a filename as follows:
echo «Coping data to /tmp/filename-$
date command FORMAT_STRING
FORMAT_STRING (FORMAT) controls the output. Interpreted sequences are as follows (taken from GNU/date man page)
- %a – locale’s abbreviated weekday name (e.g., Sun)
- %A – locale’s full weekday name (e.g., Sunday)
- %b – locale’s abbreviated month name (e.g., Jan)
- %B – locale’s full month name (e.g., January)
- %C – century; like %Y, except omit last two digits (e.g., 20)
- %d – day of month (e.g., 01)
- %D – date; same as %m/%d/%y
- %F – full date; same as %Y-%m-%d
- %g – last two digits of year of ISO week number (see %G)
- %G – year of ISO week number (see %V); normally useful only with %V
- %H – hour (00..23)
- %I – hour (01..12)
- %j – day of year (001..366)
- %m – month (01..12)
- %M – minute (00..59)
- %n – a newline
- %N – nanoseconds (000000000..999999999)
- %p – locale’s equivalent of either AM or PM; blank if not known
- %P – like %p, but lower case
- %q – quarter of year (1..4)
- %r – locale’s 12-hour clock time (e.g., 11:11:04 PM)
- %R – 24-hour hour and minute; same as %H:%M
- %s – seconds since 1970-01-01 00:00:00 UTC
- %S – second (00..60)
- %T – time; same as %H:%M:%S
- %u – day of week (1..7); 1 is Monday
- %U – week number of year, with Sunday as first day of week (00..53)
- %V – ISO week number, with Monday as first day of week (01..53)
- %w – day of week (0..6); 0 is Sunday
- %W – week number of year, with Monday as first day of week (00..53)
- %x – locale’s date representation (e.g., 12/31/99)
- %X – locale’s time representation (e.g., 23:13:48)
- %y – last two digits of year (00..99)
- %Y – year
- %z – +hhmm numeric time zone (e.g., -0400)
- %:z – +hh:mm numeric time zone (e.g., -04:00)
- %::z – +hh:mm:ss numeric time zone (e.g., -04:00:00)
- %. z – numeric time zone with : to necessary precision (e.g., -04, +05:30)
- %Z – alphabetic time zone abbreviation (e.g., EDT)
Bash shell append date to filename in Linux or Unix
Finally, you can create a filename as follows:
Источник
Shell Scripting: Create Report / Log File Names With Date in Filenames
S ometime you need to create a shell scripts with output filenames with date in it. For example instead of log file named “secure.log”, you can create a filename called “secure-jan-02-06.log” or “secure-DATE-FORMAT.log”. The DATE-FORMAT can be set as per requirements:
=> dd-mm-yyyy
=> mm-dd-yyyy
=> yyyy-mm-dd
=> Month-Day-Year
The date in the filename will make it easy to find out all logs or reports. You can display the current date and time in the given FORMAT using date command. If you just type date command it will display in standard FORMAT:
$ date
Output:
date Command Syntax
The syntax is as follows for GNU/date:
To display date in MONTH-DD-YYYY format use the date command as follows:
$ date +»%b-%d-%y»
Sample outputs:
Feb-05-06
Where, FORMAT can be any one of the following:
- %a : Abbreviated weekday name (Sun..Sat)
- %b : Abbreviated month name (Jan..Dec)
- %B : Full month name, variable length (January..December)
- %d : Day of month (01..31)
- %e : Day of month, blank padded ( 1..31)
- %m : Month (01..12)
- %Y : Year
- %d : Day of month (e.g, 01)
- %H : 24 hour format (00..23)
- %I : 12 hour format (01..12)
- %j : day of year (001..366)
- %D : date; same as %m/%d/%y
- %F : full date; same as %Y-%m-%d (a good format for sorting filename)
Get the date in YYYY-mm-dd format
To create a file with date in filename, enter:
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
To display filename, enter:
Sample Shell Script
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
IMHU, to see a sorted list of log files the best date options is “+%Y%m%d%H%M%S”. Separate fields with hyphen could make it more human readable.
When a lot of instances of your program is running simultaneously, may you should add the PID to this string.
Exactly, what kind of idiot would use the MONTH-DAY-YEAR format for filenames? Once again the comment section has a higher quality than the article.
No need to be rude. Each setup has unique requirements. So I used MM-DD-YYYY format, but that doesn’t mean I’m an idiot.
Have a nice day!
Take a look at log4sh [http://log4sh.sourceforge.net/] as well. It might be a better choice for your logging needs.
Awesome stuff, you have save me tons of time
Thank you. Very helpful.
Okay, but how do I retrieve and format YESTERDAY’s date? Or, more generally, how do I perform date “arithmetic” from a shell script (adding days / weeks, etc)?
What about to start apps via script and set today’s date to log at the time of app start?
Источник