string - 用于选择具有最新日期且不带子字符串的文件名的 Bash 脚本

标签 string bash shell ubuntu filenames

如果一个目录/dat包含具有文件名的文件,例如

base-2020-01-01.dat
base-2020-01-01-incremental-2020-01-02.dat
base-2020-01-01-incremental-2020-01-03.dat
base-2020-01-03.dat
base-2020-01-03-incremental-2020-01-04.dat
base-2020-01-03-incremental-2020-01-05.dat
我们如何编写一个选择的 bash 脚本
  • base-*.dat不带 -incremental-* 的文件名子字符串,并且文件名中的日期是最近的日期。
  • 此文件名中的日期字符串

  • 在本例中,我们要选择 base-2020-01-03.dat2020-01-03 .
    如果不同的文件命名约定更容易解析,那就更好了!

    最佳答案

    与现代 GNU工具:使用 find , grep -Pbash (带错误处理)

    read file < <(
      find /data -maxdepth 1 -name 'base*.dat' ! -name '*incremental*' \
        -printf '%f\n' | sort -nr | head -n1
    )
    set -e
    echo "${file:?$(tput setaf 1)no match$(tput sgr0;exit 1)}"
    date=$(grep -oP "\d{4}-\d{2}-\d{2}" <<< "$file")
    echo "$date"
    
    输出
    base-2020-01-03.dat
    2020-01-03
    

    关于string - 用于选择具有最新日期且不带子字符串的文件名的 Bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62685725/

    相关文章:

    xml - 从字符串(不是文件)获取 XML

    bash - 在指定模式之前在文件中插入多行

    linux - Bash - 在脚本中执行命令,将单引号添加到包含空格的变量

    Java8 : Create HashMap with character count of a String

    java - 使用 StringUtils 方法比 Java 方法运行得更快?

    c++ - 如何检查字符串是否超过 256 个字节?

    regex - Sed 使用正则表达式从文件中删除时间戳

    bash - 有没有一种方法可以使用 bash shell 逐行组合两个文件

    linux - 如何从 bash 中的字符串中获取数值

    c++ - 打开失败 : No such file or directory