Bash 脚本根据文件时间戳创建目录,并移动到相应的目录中
我每天都创建很多名为test_file_201701011512000.dat的文件。我需要移动这些文件的日期或月份明智的目录,如果目录并没有创建,然后创建相应的。请建议如何操作。您可以这样做,假设您的所有文件都在同一目录中。文件将移动到dest/year/month目录:Bash 脚本根据文件时间戳创建目录,并移动到相应的目录中,bash,shell,scripting,Bash,Shell,Scripting,我每天都创建很多名为test_file_201701011512000.dat的文件。我需要移动这些文件的日期或月份明智的目录,如果目录并没有创建,然后创建相应的。请建议如何操作。您可以这样做,假设您的所有文件都在同一目录中。文件将移动到dest/year/month目录: #!/bin/bash dest_dir=_your_destination_directory_ # pattern to grab 4 digits of year and 2 digits of month file
#!/bin/bash
dest_dir=_your_destination_directory_
# pattern to grab 4 digits of year and 2 digits of month
file_pattern="_([[:digit:]]{4})([[:digit:]]{2})"
for file in test_file_*; do
[[ ! -f $file ]] && continue # look at regular files only
if [[ $file =~ $file_pattern ]]; then
year="${BASH_REMATCH[1]}"
month="${BASH_REMATCH[2]}"
destination_dir="$dest_dir/$year/$month"
[[ ! -d $destination_dir ]] && mkdir -p "$destination_dir"
echo "Moving $file to $destination_dir"
mv "$file" "$destination_dir"
fi
done
到目前为止,你写了什么?@codeforester:这似乎不重要,因为你都是为他们写的;如果你只是做别人的工作,而他们在这个过程中什么也学不到,那你就什么也得不到了。您的回答没有解释函数的功能…非常感谢它的工作,但是月份仅显示为2位数字,即12,11,10,但我想要像201312201401402402这样的月份,请建议可以更改的地方。这是一个小更改-您必须删除$year和$month之间的
/
。