[英]Rename certain files recursively in a directory - Shell/Bash script
I've searched about everywhere, to come up with this script below. 我到处搜索过,以在下面找到此脚本。 I can't figure out what the issue is here. 我不知道这里是什么问题。 I'm trying to loop through all the directories inside a directory called Extracted_Source to rename any files that is a CSV with an appended timestamp. 我试图遍历名为Extracted_Source的目录内的所有目录,以重命名带有CSV时间戳的任何文件。 Any help is appreciated. 任何帮助表示赞赏。
I keep getting a 我不断得到
No such file or directory./Extracted_Source/*
Below is the source: 以下是来源:
for files in ./Extracted_Source/*
do if ["$files" contains ".csv"]
then mv "$files" "${files%}_$(date "+%Y.%m.%d-%H.%M.%S").csv";
fi done; echo end
I would use find
我会用find
find ./Extracted_Source -type f -name "*.csv" | while -r read files; do mv "$files" "${files%.*}_$(date "+%Y.%m.%d-%H.%M.%S").csv"; done
This also has the added benefit of handling files containing spaces in the file name. 这还具有处理文件名中包含空格的文件的额外好处。
Here's the same thing in multi-line form: 这是多行形式的同一件事:
find ./Extracted_Source -type f -name "*.csv" | \
while read -r files; do
mv "$files" "${files%.*}_$(date "+%Y.%m.%d-%H.%M.%S").csv"
done
You can also use process substitution to feed the while
loop: 您还可以使用进程替换来填充while
循环:
while read -r files; do
mv "$files" "${files%.*}_$(date "+%Y.%m.%d-%H.%M.%S").csv"
done < <(find ./Extracted_Source -type f -name "*.csv")
In your current script, ${files%}
is not doing anything. 在您当前的脚本中, ${files%}
没有执行任何操作。 The .csv
part of the file is not being removed. 文件的.csv
部分没有被删除。 The correct way is ${files%.*}
. 正确的方法是${files%.*}
。
Try this to see for yourself: for files in *; do echo "${files%.*}"; done
试试看一下: for files in *; do echo "${files%.*}"; done
for files in *; do echo "${files%.*}"; done
See the Bash Hackers Wiki for more info on this. 有关更多信息,请参见Bash Hackers Wiki 。
For a start, the error message means that you don't have any files or folders in ./Extracted_Source/
. 首先,该错误消息表示./Extracted_Source/
没有任何文件或文件夹。 However, the following will work: 但是,以下方法将起作用:
#!/bin/bash
for file in ./Extracted_Source/*/*.csv; do
mv "$file" "${file/.csv}_$(date "+%Y.%m.%d-%H.%M.%S").csv";
done
echo end
This doesn't account for csv files which have already been moved. 这不考虑已移动的csv文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.