Shell

從“abcd.log.2017_01_26_23_30.0”等文件名中提取日期“2017-01-26”(yyyy-mm-dd)

  • February 15, 2017

我在下面有一些文件/mainFolder/test

abcd.log.2017_01_26_23_30.0
abcd.log.2017_01_26_23_35.0
abcd.log.2017_02_20_23_10.0
xyz1.log.2017-02-01
xyz2.log.2017-03-11

從這些文件中,我需要一個像abcd.log.2017_01_26_23_30.0. 要搜尋,我正在嘗試:

myRegex="[0-9]{4}_[0-9]{2}_[0-9]{2}_[0-9]{2}_[0-9]{2}.[0-9]{1}"
realPath="/mainFolder/test/abcd.log.2017_01_26_23_30.0"
[[ $realPath =~ $myRegex ]] && echo "It is matching" || echo "Does not match"

獲取文件後,我需要以格式提取日期yyyy-mm-dd(即我需要2017-01-26)。

我怎樣才能做到這一點?

使用擷取組並$BASH_REMATCH提取字元串位:

for name in *.log.*; do
   if [[ "$name" =~ \.([0-9]{4})_([0-9]{2})_([0-9]{2}) ]]; then
       printf '%d-%d-%d from "%s"\n' \
           "${BASH_REMATCH[1]}" \
           "${BASH_REMATCH[2]}" \
           "${BASH_REMATCH[3]}" \
           "$name"
   fi
done

輸出:

2017-01-26 from "abcd.log.2017_01_26_23_30.0"
2017-01-26 from "abcd.log.2017_01_26_23_35.0"
2017-02-20 from "abcd.log.2017_02_20_23_10.0"

如果您需要變數中的日期字元串:

for name in *.log.*; do
   if [[ "$name" =~ \.([0-9]{4})_([0-9]{2})_([0-9]{2}) ]]; then
       datestring="$( printf '%d-%d-%d' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" "${BASH_REMATCH[3]}" )"
       printf '%s from "%s"\n' "$datestring" "$name"
   fi
done

ksh93,替換BASH_REMATCH.sh.match

引用自:https://unix.stackexchange.com/questions/345157