移动包含空格的所有匹配文件,并在bash中添加带通配符的不同文本

时间:2016-01-16 06:30:02

标签: bash unix rename wildcard mv

我有一个每天生成报告的目录,我正在编写一个脚本,将旧报告移动到废纸篓并在生成下一个报告之前重命名。

e.g。目录

File Report - Sat 16-01-2016.txt

由于文件始终使用相同的常量生成'文件\报告 - ' e.g。

File Report - Tue 12-01-2016.txt
File Report - Wed 13-01-2016.txt
File Report - Thur 14-01-2016.txt
File Report - Fri 15-01-2016.txt

我以为我可以使用像这样的一些bash代码。

mv -f ~/Desktop/File\ Report\*.txt ~/.Trash/"Old File Report".txt

但是我想添加“#34; Old"在文件的前面,同时保持随后的日期和日期。 e.g。

File Report - Tue 12-01-2016.txt

会变成

Old File Report - Tue 12-01-2016.txt

我以为我可以使用变量并将文件名存储在其中。我不确定如何编码,但它会是这样的。

OLD=$(echo ~/Desktop/'File Report - '*.txt)
mv -f ~/Desktop/File\ Report\*.txt ~/.Trash/"Old "$OLD.txt

我知道这是非常错误的语法。我目前正在阅读包括find在内的一些手册页,看看这样的东西是否更适合抓取文件名以将其存储到变量中。

2 个答案:

答案 0 :(得分:0)

这是一个非常基本的shell循环:

for report in ~/Desktop/'File Report'*.txt; do
  mv "$report" ~/.Trash/"Old ${report##*/}"
done

循环变量将包含文件的完整路径;我们使用shell的内置${variable##prefix}字符串替换机制从目标文件名修剪目录部分。

顺便说一句,如果您想将旧名称分配给另一个变量,那么您不需要echo

old=$report

您不应该使用大写变量名称,因为它们是为shell自己的变量保留的(PATHPS1等)。

答案 1 :(得分:-1)

看起来你真的需要遍历文件结果。我会使用find并尝试这样的事情。

cd ~/REPORT_FOLDER
find . -name 'File Report*.txt' -exec mv {} '~/.Trash/Old {}.txt'

或者取结果并将它们放入实际的for循环中:

cd ~/REPORT_FOLDER
for report in $( find . -name 'File Report*.txt'); do
  mv $report ~/.Trash/"Old $report"
done