#!/bin/bash
# When a match is not found, just present nothing.
shopt -s nullglob
# Match all .wav files containing the date format.
files=(*[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*.wav)
if [[ ${#files[@]} -eq 0 ]]; then
echo "No match found."
fi
for file in "${files[@]}"; do
# We get the date part by part
file_date=''
# Sleep it to parts.
IFS="-." read -ra parts <<< "$file"
for t in "${parts[@]}"; do
# Break from the loop if a match is found
if [[ $t == [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] ]]; then
file_date=$t
break
fi
done
# If a value was not assigned, then show an error message and continue to the next file.
# Just making sure there is nothing in Array and date before it moves on
if [[ -z $file_date ]]; then
unset $files
continue
fi
file_year=${file_date:0:4}
file_month=${file_date:4:2}
echo $file_year
echo $file_month
echo mkdir -p $file_year/$file_month
mkdir -p "$file_year/$file_month"
# -- is just there to not interpret filenames starting with - as options.
echo "$file" "$file_year/$file_month"
mv "$file" "$file_year/$file_month"
done
所以在运行我的代码之后,我的输出就是这个我的DIR 201211,201212,201301,201302,201303,201304,所以我尝试运行这个因为我有YYYYMMDD的文件并且想要制作DIR年份然后在里面我想要DIR月份然后提交。有时我可以得到一个DIR2013 / 06 /文件,但由于一些奇怪的原因我得到DIR201304 /文件。我不明白这个问题是什么.......我在大约1.1 Terabite上运行这个脚本
答案 0 :(得分:0)
bash可以做正则表达式,所以你可以这样做:
filename="blah.blah-12345678.ext"
if [[ $filename =~ [.-]([0-9]{4})([0-9]{2})[0-9]{2}[.-] ]]; then
echo year=${BASH_REMATCH[1]} month=${BASH_REMATCH[2]}
fi
year=1234 month=56
BASH_REMATCH
是一个数组,用于保存索引0中字符串的匹配部分,其他索引保存括号中捕获的部分。