如何使用正则表达式从文件路径和名称解析日期和时间?
我有文件存储在这样的文件夹中
/home/user/folder/sub/2017-20-10/001/jpg/14/48/31[M][0@0][0].jpg
基本上,这告诉我该图像是在2017-20-10 14:48:31
从相机001
拍摄的
我想将此文件复制到一个新位置,名称为从路径+名称解析的日期和时间,因此新文件将是 20172010144831.jpg
最好的方法是什么?我认为正则表达式。这个表达式会是什么样子?
最佳答案
理想情况下,您不必复制正则表达式和迭代模式,但这至少简单且易于理解。
regex=/home/user/folder/sub/(....-..-..)/(.*)/jpg/(..)/(..)/(..).*\.jpg
for f in /home/user/folder/sub/*/*/jpg/*/*/*.jpg; do
# Match against the regex, or skip to the next file
[[ $f =~ $regex ]] || continue
# The first capture group is the date. Strip the -.
d=${BASH_REMATCH[1]//-}
# The next three capture groups are the hour, minute, and second
t=("${BASH_REMATCH[@]:2:3}")
printf -v new_name '%s%s%s%s.jpg' "$d" "${t[@]}" # Put them all together
done
关于regex - 从文件名和路径解析日期和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46848583/