bash 如何从目录复制文件并将日期附加到文件名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18160827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to copy files from dir and append date to filename?
提问by Matkrupp
I'm trying to copy files from one directory to another and append current date to this filename. The script look like this
我正在尝试将文件从一个目录复制到另一个目录并将当前日期附加到该文件名。脚本看起来像这样
#!/bin/bash
echo 'Move to homedir'
cd $HOME
echo 'Copy .txt files'
NOW=$(date +"%d%m%Y")
for FILENAME in *.txt
do
cp "${FILENAME}" "/newdir/${FILENAME}${NOW}"
done
This generates an error because date is appended after file extension, like this
这会产生错误,因为日期附加在文件扩展名之后,如下所示
file1.txt10082013
file1.txt10082013
How to avoid that?
如何避免这种情况?
回答by cnicutar
Try extracting the extension and renaming the file:
尝试提取扩展名并重命名文件:
NAME="${FILENAME%.*}"
EXT="${FILENAME##*.}"
cp "${FILENAME}" "/newdir/${NAME}${NOW}.${EXT}"