Добавьте дату к имени файла в Linux

тест @Adam использовал

"these are " . $foo

примечание, что следующее еще быстрее:

'these are ' . $foo;

это происходит из-за того, что двойная заключенная в кавычки "строка" оценена, где единственная заключенная в кавычки 'строка' просто взята, как...

26
задан sami 25 November 2009 в 10:49
поделиться

4 ответа

Вы можете использовать обратные кавычки.

$ echo "myfilename-"`date +"%d-%m-%Y"`

Выводит:

myfilename-25-11-2009
33
ответ дан 28 November 2019 в 06:10
поделиться
cp somefile somefile_`date +%d%b%Y`
16
ответ дан 28 November 2019 в 06:10
поделиться

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
40
ответ дан 28 November 2019 в 06:10
поделиться

немного более запутанное решение, которое полностью соответствует вашей спецификации

echo `expr $FILENAME : '\(.*\)\.[^.]*'`_`date +%d-%m-%y`.`expr $FILENAME : '.*\.\([^.]*\)'`

, где первый 'expr' извлекает имя файла без расширения, второй 'expr' извлекает расширение

0
ответ дан 28 November 2019 в 06:10
поделиться
Другие вопросы по тегам:

Похожие вопросы: