【发布时间】:2019-11-13 03:03:13
【问题描述】:
从该文件名中提取时间并将其转换为自当天 00:00 以来的秒数(无时间戳)并使用 pure bash 的最佳方法是什么?
/a/very/long/path/to/my/files/2019-07-02_06_12_55_SOME_FOO_BAR.log
预期输出:
extractTimeinSecond() {
// code
}
filetime=$(extractTimeinSecond $file)
echo $filetime # 22375
我会做这样的事情,但这不是很性感,因为我确信有更好的方法来获得它。
extractTimeinSecond() {
file=$1 # /a/very/long/path/to/my/files/2019-07-02_06_12_55_SOME_FOO_BAR.log
shortfile=$(basename $file) # 2019-07-02_06_12_55_SOME_FOO_BAR.log
time=$(echo $shortfile | cut -d '_' -f 2,3,4) # 06_12_55
h=$(( $(echo $time | cut -d '_' -f1) * 60 * 60 )) # 06 * 60 * 60 = 21600
m=$(( $(echo $time | cut -d '_' -f2) * 60 )) # 12 * 60 = 720
s=$(echo $time | cut -d '_' -f3) # 55
echo $(( $h + $m + $s )) # 21600 + 720 + 55 = 22375
}
【问题讨论】:
-
cut和basename不是纯 bash。
标签: string bash shell time extraction