Bash 脚本提取子字符串,转换为整数

Bash script to extract substring, convert to integer

我正在编写一个 Bash 脚本,该脚本执行 returns 字符串形式为

的命令

/folder/file_NNNN llll.killAt="nn...nn"

我想做以下事情

我的 bash 技能有限。我尝试通过发出

来识别 killAt 部分的索引
ndx=`expr index "$rslt" killAt` 

我的想法是,一旦我拥有索引,我就可以提取数字位并对其进行处理。但是,我在 ndx 中得到的根本不是 KillAt 的位置,所以很明显我犯了一个错误。我不确定要搜索的字符串中存在 /、- 和 " 不会造成问题。

我可以通过 运行 一个 PHP 脚本来完成上述所有操作,但如果我这样做的话会更多,因为我无法正确使用 Bash 脚本。

expr 实际上只需要在 POSIX shell 中进行正则表达式匹配。它的所有其他功能都在 bash 本身中实现。

# A regular expression to match against the file name.
# Adjust as necessary; the (.*) is capture group to
# extract the timestamp.
regex='/folder/file_???? ????\.killAt="(.*)"'
# Match, and if it succeeds, retrieve the captured time
# from the BASH_REMATCH array.
if [[ $rslt =~ $regex ]]; then
    ndx=${BASH_REMATCH[1]}
    if (( ndx > $(date +%s) )); then
        rm "$rslt"
    fi
fi