从Bash中的文件名中提取日期的实用程序? [英] Utility to extract dates from filenames in Bash?

查看:49
本文介绍了从Bash中的文件名中提取日期的实用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从以下文件名中获取 $ YEAR $ MONTH $ DAY 变量:

How can I get $YEAR, $MONTH, and $DAY variables from the following filenames:

201601010557 - Development Database.bak
Screen Shot 2017-01-11 at 10.42.14 PM
SIRIUS Internet Radio - Howard 100 20101220 0600.mp3
Howard Stern Show - 20160413.mp3

我正在尝试按名称中的日期来组织文件.但是,我很难理解 sed grep 命令.这些文件包含三种不同格式的日期.

I'm trying to organize files by the date within the name. However, I'm having difficulty understanding the sed and grep commands. The files contain dates in three different formats.

我找到了一个示例,该示例在带连字符日期的文件上效果很好,但是它对 sed 使用了#占位符(这导致我的大脑受伤).我宁愿有一个 $ YEAR $ MONTH $ DAY 变量,这样我可以更好地理解它并根据自己的喜好对函数进行调整(即按月订购按年订购).

I've found one example that works well on files with the hyphenated date, but it uses # placeholders for sed (which is causing my brain to hurt). I would much rather have a $YEAR, $MONTH, and $DAY variable so I can understand it better and tweak the function to my liking (ie order-by-month or order-by-year).

org-by-date(){
    ls -A1 | grep -E '[0-9]{4}-[0-9]{2}-[0-9]{2}' | while read -r line; do
        DNAME="$(echo $line | grep -Eo '[[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}' | sed 's#-#/#g')"
        mkdir -p "./$DNAME"
        mv "$line" "./$DNAME/"
    done
}

是否有更简单的方法来获取日期变量?例如:

Is there an easier way to get the date variables? For example:

order-by-date(){
    ls -A1 | grep -E '( ... magic pattern here ... )' | while read -r line; do
        YEAR="$(echo $line....)
        MONTH="$(echo $line....)
        DAY="$(echo $line....)

        # ... and in a perfect world, get times IF they exist...
        HOUR="$(echo $line....)
        MINUTE="$(echo $line....)
        SECOND="$(echo $line....)
    done
}

推荐答案

使用正则表达式和参数扩展:

for i in *; do
  [[ $i =~ [0-9]{8}|[0-9]{4}-[0-9]{2}-[0-9]{2} ]]
  x="${BASH_REMATCH[0]//-/}"
  y="${x:0:4}"
  m="${x:4:2}"
  d="${x:6:2}"
  echo "$y $m $d"
done | sort -n

输出:


2010 12 20
2016 01 01
2016 04 13
2017 01 11

这篇关于从Bash中的文件名中提取日期的实用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆