简体   繁体   中英

Define string/timestamp match a regex in Bash script

I have to read from a file in bash script and always confirm that if the timestamp on each line is valid before doing anything. My timestamp looks like this:

Mar 15 14:20:48

I want to check if all timestamps I read will have the correct format. I tried doing it via:

(date -d ...)

But this tends to pass even if date looks like this: Mar 15 14:2

I was told to use regex to define what the date looks like so I was using this

if [["${LASTTS}" =~ ^[a-zA-Z]+ [0-3][0-9]+ [0-2][0-9]:[0-5][0-9]:[0-5][0-9]$ ]]; then

But keep getting error saying line 38: [[Mar 15 14:20:48: command not found

I believe it might be easier to ask date to do a conversion to the expected format and do a check if the input-date-format and the output-date-format is identical. If they are identical, the input-date-string is a valid string:

If you use the following command, it will convert the string to your valid format:

date -d "input-date" "+%b %d %T"
  • In impossible input date will return an empty string:
  • An invalid input date will return a different string

Examples"

input-date (d1) | output-date (d2)| d1 == d2 | input valid
----------------+-----------------+----------+-------------
Mar 15 14:02:15 | Mar 15 14:02:15 | yes      | yes
Mar 15 14:2     | Mar 15 14:02:00 | no       | no
Mar 32 14:02:15 |                 | no       | no
Mak 15 14:02:15 |                 | no       | no
Mar 15 24:02:15 |                 | no       | no

So your test would look like:

d1="Mar 15 14:20:48"
d2=$(date -d "$d1" "+%b %d %T" 2> /dev/null)
if [[ "$d1" == "$d2" ]]; then
   echo "the dates are the same"
fi

This method is a bit safer than using a regular expression as many strings might pass the regular expression but are not a valid date. A Simple example would be "XYZ 39 29:59:12"

In case of the OP's question, it would read:

if [[ "${LASTTS}" == $(date -d "${LASTTS}" "+%b %d %T" 2> /dev/null) ]]; then

Assuming your format is always the same as "Mar 15 14:20:48" if correct, then it should always match +'%b %d %T' . If so, you can verify not only the format but the content with date .

$: ts='Mar 15 14:20:48' # valid date/time in correct format
$: [[ "$ts" == "$( date +'%b %d %T' -d "$ts" )" ]] && echo ok || echo mismatch
ok
$: ts='Mar 15 14:2' # valid date/time in wrong format
$: [[ "$ts" == "$( date +'%b %d %T' -d "$ts" )" ]] && echo ok || echo mismatch
mismatch
$: ts='Feb 31 14:20:48' # invalid date/time in correct format
$: [[ "$ts" == "$( date +'%b %d %T' -d "$ts" )" ]] && echo ok || echo mismatch
date: invalid date ‘Feb 31 14:20:48’
mismatch

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM