Append date to filename in linux

Viewed 161264

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

7 Answers

You can add date next to a filename invoking date command in subshell.

date command with required formatting options invoked the braces of $() or between the backticks (`…`) is executed in a subshell and the output is then placed in the original command.

The $(...) is more preferred since in can be nested. So you can use command substitution inside another substitution.

Solutions for requests in questions

$ echo somefile_$(date +%d-%m-%Y).txt
somefile_28-10-2021.txt

$ echo somefile_$(date +%d%b%Y).txt
somefile_28Oct2021.txt

The date command comes with many formatting options that allow you to customize the date output according to the requirement.

  • %D – Display date in the format mm/dd/yy (e.g. : 10/28/21)
  • %Y – Year (e.g. : 2021)
  • %m – Month (e.g. : 10)
  • %B – Month name in the full string format (e.g. : October)
  • %b – Month name in the shortened string format (e.g. : Oct)
  • %d – Day of month (e.g. : 28)
  • %j – Day of year (e.g. : 301)
  • %u – Day of the week (e.g. : 4)
  • %A – Weekday in full string format (e.g. : Thursday)
  • %a – Weekday in shortened format (e.g. : Thu)

I use this script in bash:

#!/bin/bash

now=$(date +"%b%d-%Y-%H%M%S")
FILE="$1"
name="${FILE%.*}"
ext="${FILE##*.}"

cp -v $FILE $name-$now.$ext

This script copies filename.ext to filename-date.ext, there is another that moves filename.ext to filename-date.ext, you can download them from here. Hope you find them useful!!

I use it in raspberry pi, and the first answer doesn't work for me, maybe because I typed wrong or something? I don't know. So I combined the above answers and came up with this:

now=$(date +'%Y-%m-%d')
geany "OptionalName-${now}.txt"

That if you want to use geany or anything else

enter image description here enter image description here

Related