【问题标题】:Bash string replacement with regex repetition使用正则表达式重复替换 Bash 字符串
【发布时间】:2013-02-01 11:34:29
【问题描述】:

我有一个文件:filename_20130214_suffix.csv 我想替换 bash 中的 yyyymmdd 部分。这是我打算做的:

file=`ls -t /path/filename_* | head -1`
file2=${file/20130214/20130215}
#this will not work
#file2=${file/[0-9]{8}/20130215/}

【问题讨论】:

    标签: regex string bash replace repeat


    【解决方案1】:
    [[ $file =~ ^([^_]+_)[0-9]{8}(_.*) ]] && file2="${BASH_REMATCH[1]}20130215${BASH_REMATCH[2]}"
    

    【讨论】:

      【解决方案2】:

      问题是参数扩展不使用正则表达式,而是模式或glob(比较正则表达式“filename_..csv”和glob“filename_.csv”之间的区别)。 Glob 无法匹配固定数量的特定字符串。

      但是,您可以在bash 中启用扩展模式,它应该与您想要的足够接近。

      shopt -s extglob    # Turn on extended pattern support
      file2=${file/+([0-9])/20130215}
      

      您不能完全匹配 8 个数字,但 +(...) 允许您匹配括号内的一个或多个模式,这对于您的用例来说应该足够了。

      由于在这种情况下您要做的就是替换 _ 字符之间的所有内容,因此您也可以简单地使用

      file2=${file/_*_/_20130215_}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        • 1970-01-01
        • 2018-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-16
        相关资源
        最近更新 更多