从文件名和路径

时间:2017-10-20 11:56:47

标签: regex bash

如何使用正则表达式从文件路径和名称解析日期和时间?

我将文件存储在像这样的文件夹中

/home/user/folder/sub/2017-20-10/001/jpg/14/48/31[M][0@0][0].jpg

基本上这告诉我图像来自001上的相机2017-20-10 14:48:31

我想将此文件复制到一个新位置,其名称为从路径+名称解析的日期和时间,因此新文件将为20172010144831.jpg

最好的方法是什么?我会假设正则表达式。这个表达式会是什么样的?

2 个答案:

答案 0 :(得分:3)

理想情况下,您不必复制正则表达式和迭代模式,但这至少是直截了当且易于理解。

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    

答案 1 :(得分:0)

具有特定正则表达式模式的

Y=zeros(size(X)); for k=1:length(X) Y(k) = 6113 * cos(2*pi*200*X(k) + 1508); end plot(X,Y) + find 解决方案:

bash
  • find . -type f -regextype posix-egrep \ -regex ".*/[0-9]{4}-[0-9]{2}-[0-9]{2}/[0-9]+/jpg/[0-9]{2}/[0-9]{2}/[0-9]{2}.*.jpg$" \ -exec bash -c 'shopt -s extglob; pat="/([0-9]{4})-([0-9]{2})-([0-9]{2})/[0-9]+/jpg/([0-9]{2})/([0-9]{2})/([0-9]{2})"; [[ "$0" =~ $pat ]]; items="${BASH_REMATCH[@]:1:6}"; cp "$0" "dest_dir/${items// /}.jpg"' {} \; - 是您的新位置