Check if a string matches a given date

I need my bash script to accept a date format string ("strftime" format) like:

<[% Y-% m-% d% H:% M:% S] →

Then check if the data (left value) in my input file matches the given line or not:

Format string: <<<<<<<>% Y %% -% d% H:% M:% S] → Data file:
<<<[2017-05-04 14:49:18] → 12.1 - valid
<[2017-05-04 14:49:18]> -1421 - invalid
<[05-04-2017 14:49:18] → 1231231.02 - invalid

The input file has many lines and the only thing I came up with is using Python:

function check_time_format() {
    python -c "import time; 
time.strptime(\"$1\",\"$2\")" 2> /dev/null
}

while read -r lvalue rvalue; do
    check_time_format "$lvalue" "$TIMEFORMAT"
    [[ $? != 0 ]] && echo "Invalid format..."
done < "$file"

      

It works, but it is of course very slow. Is there a better way to do this, possibly just as easily?

Thank!

+3


source to share


2 answers


I ended up resorting to a solution that I wanted to avoid. I just let python process the whole file instead of bash.



0


source


The easiest way to do this is to use date

for interpretation, then reformat the date in the given format, and then compare it to the original input:



is_in_format() {
    local fmt="$1" datestring="$2"
    if [ ! "x$(date "+$fmt" --date="$datestring")" = "x$datestring" ]; then
        echo "Unrecognized date format: $datestring - use format $fmt" >&2
        return 2
    fi
    return 0
}

is_in_format "%F" '2017-06-01' # true
is_in_format "%F %H:%M" '2017-06-01' # false

      

0


source







All Articles