Bash 如何重命名保存到变量中的文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15546208/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:56:23  来源:igfitidea点击:

Bash how can rename a file saved into a variable?

bashcopyfile-rename

提问by rschirin

how can I do this:

我怎样才能做到这一点:

I have a file, eval.txtsaved into a variable, that I want to rename timestamp_eval.txt

我有一个文件,eval.txt保存到一个变量中,我想重命名timestamp_eval.txt

filetosend=/home/cft/eval.txt
filename=$(echo $filetosend | cut -d '/' -f4) //to get only the name
DATE=$(date +%Y%m%d)
filename=${DATE}_${filename} //add timestamp to name

how can I rename $filetosend?

我该如何重命名$filetosend

I found this solution:

我找到了这个解决方案:

DATE=(date +%Y%m%d)
mydir=$(echo $(dirname $a))
myfile=$(echo $(basename $a))
myfile=${DATE}_${myfile}
filetosend=$mydir/$myfile
cp $a $filetosend

回答by Gilles Quenot

Try doing this if you really need a variable:

如果您确实需要一个变量,请尝试这样做:

filetosend=/home/cft/eval.txt
cd "${filetosend%/*}"
filename="${filetosend##*/}"
DATE=$(date "+%Y%m%d")
filename="${DATE}_$filename"
mv "$filetosend" "$filename"

If you don't really need a variableusing rename:

如果你并不真的需要一个变量使用rename

rename "s|[^/]+$|$(date +%Y%m%d)_$&|" /home/cft/eval.txt

or decomposed on multi-lines :

或在多行上分解:

cd /home/cft/
rename "s/.*/$(date "+%Y%m%d")_$&/" eval.txt
rename "s|[^/]+$|$(date "+%Y%m%d")_$&|"

Note

笔记

Read this postto know if you have the good renameon your system + extra explanations.

阅读这篇文章以了解rename您的系统是否有优势+ 额外的解释。

回答by Chris Seymour

The simplest way would be to do:

最简单的方法是:

mv /home/cft/eval.txt /home/cft/$(date "+%Y%m%d")_eval.txt

回答by Benubird

Using the mv command. "mv" is short for "move".

使用 mv 命令。“mv”是“移动”的缩写。

mv $filetosend $filename