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
I'd use YYYY-MM-DD HHmmss for filenames, unless there is a particular need for timezones or a possible need to parse them into ISO dates; in those cases an ISO date would probably be preferrable.
You should use double quotes and need to evaluate date +"%F" using command substitution. Double quote helps you create a single file where some options of date command would include a space. For example, touch test_$(date) will create multiple files, where as touch "test_$(date)" won't.
You do this by using the append redirection symbol, ``>>''. To append one file to the end of another, type cat, the file you want to append, then >>, then the file you want to append to, and press <Enter>.
You can use backticks
.
$ echo myfilename-"`date +"%d-%m-%Y"`"
Yields:
myfilename-25-11-2009
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.
$ DATE=`date +%d-%m-%y`
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.
$ NAME=`echo $FILE | cut -d. -f1 $ EXT=`echo $FILE | cut -d. -f2`
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:
$ NAME=${FILE%.*} $ EXT=${FILE#*.}
Putting them together we get:
$ FILE=somefile.txt $ NAME=${FILE%.*} $ EXT=${FILE#*.} $ DATE=`date +%d-%m-%y` $ NEWFILE=${NAME}_${DATE}.${EXT} $ echo $NEWFILE somefile_25-11-09.txt
And if we're less worried about readability we do all the work on one line (with a different date format):
$ FILE=somefile.txt $ FILE=${FILE%.*}_`date +%d%b%y`.${FILE#*.} $ echo $FILE somefile_25Nov09.txt
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With