在Linux中将日期附加到文件名 [英] Append date to filename in linux

查看:390
本文介绍了在Linux中将日期附加到文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在文件名("somefile.txt")旁边添加日期.例如:somefile_25-11-2009.txt或somefile_25Nov2009.txt或具有这种效果的任何内容

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

在终端窗口中可能会执行脚本或执行某些命令.我正在使用Linux(Ubuntu).

Maybe a script will do or some command in the terminal window. I'm using Linux(Ubuntu).

谢谢.

哦,我几乎忘了补充一点,每次要将文件保存到特定文件夹但仍保留以前的文件时,脚本或命令都应将文件名更新为新日期.因此,最终该文件夹中将存在这样的文件:filename_18Oct2009.txt,filename_9Nov2009.txt,filename_23Nov2009.txt

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

推荐答案

这里有两个问题.

1.以字符串形式获取日期

这很容易.只需将date命令与+选项一起使用.我们可以使用反引号来捕获变量中的值.

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` 

您可以使用%选项来更改日期格式. title =日期手册页">日期手册页.

You can change the date format by using different % options as detailed on the date man page.

2.将文件拆分为名称和扩展名.

这有点棘手.如果我们认为它们只是文件名中的一个.,则可以使用cut.作为分隔符.

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`

但是,这不适用于文件名中的多个..如果您使用的是bash-您可能会使用- bash魔术,它使我们能够在进行变量扩展时匹配模式:

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

这篇关于在Linux中将日期附加到文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆