问题
I have strftime format of time, let's say (%Y-%m-%d %H:%M:%S)
and a file which should contain this kind of data e.g. (2012-02-11 17:15:00)
. I need to check if given pattern actually matches the data.
How to approach this? awk, date?
EDIT: More info: The user enters the strftime format, let's say on input. Then he enters a file which should contain those dates. I need to make sure, that those data are valid (he didn't make a mistake). So I need to check the rows in the input file and see, if there are data that matches the given pattern. Example:
user enters strftime format:
(%Y-%m-%d %H:%M:%S)
input file:
(2012-02-11 17:15:00) long sentence
VALID
user enters strftime format:
Date[%Y.%m.%d %H:%M:%S]
input file:
Date-2012.02.11 17:15:00- long sentence
INVALID
回答1:
If you allow an external helper binary, I've written dateutils to batch process date and time data.
dconv -q -i '(%Y-%m-%d %H:%M:%S)' <<EOF
not a match: 2012-04-10 12:00:00
a match: (2012-04-10 13:00:00)
EOF
will give
2012-04-10T13:00:00
-i
is the input format, -q
suppresses warnings. And dconv
tries to convert input lines to output lines (in this case it converts matching lines to ISO standard format.
So using this, a file matches completely if the number of input lines equals the number of output lines.
回答2:
If you want to check current datetime:
echo "(2012-02-11 17:15:00)" | grep "$(date "+%Y-%m-%d %H:%M:%S")"
If some other you need GNU date (-d option). This works for me:
echo "(2012-02-11 17:15:00)" |
grep "$(date -d "2012-02-11 17:15:00" "+%Y-%m-%d %H:%M:%S")"
回答3:
I would take a brute force approach to this: replace any %X
specifier with a corresponding regular expression, then you can filter out lines that don't match the resulting generated regex:
user_format="%Y-%m-%d"
awk -v fmt_string="$user_format" '
BEGIN {
gsub(/[][(){}?|*+.]/ "\\&", fmt_string) # protect any regex-special chars
gsub(/%Y/, "([0-9]{4})", fmt_string)
gsub(/%m/, "(0[1-9]|1[012])", fmt_string)
gsub(/%d/, "(0[1-9]|[12][0-9]|3[01])", fmt_string)
# and so on
}
$0 !~ "^" fmt_string {print "line " NR " does not match: " $0}
' filename
来源:https://stackoverflow.com/questions/10085538/check-if-given-strftime-format-matches-a-date