简体   繁体   English

如何执行日期格式

[英]how to enforce a date format

I want to use the date command to output a day of week from user input. 我想使用date命令从用户输入中输出星期几。

I want to force the input to be of the format MM/DD/YYYY. 我想强制输入格式为MM / DD / YYYY。

For example, at the command line I give 例如,在命令行中

./programname MM/DD/YYYY MM/DD/YYYY

Snippets from the script itself 脚本本身的片段

#!/bin/bash

DATE_FORMAT="^[0-9][0-9][/][0-9][0-9][/][0-9][0-9][0-9][0-9]$" #MM/DD/YYYY
DATE1="$1"
DATE2="$2"

... followed by ... 其次是

if [ "$DATE1" != "$DATE_FORMAT" ] || [ "$DATE2" != "$DATE_FORMAT" ]; then 
    echo -e "Please follow the valid format MM/DD/YYYY.\n" 1>&2
    exit 1

Now the problem is even when I enter correct date formats, 现在的问题是,即使我输入正确的日期格式,

./programname 11/22/2014 11/23/2014

I still get that error message that I set up, which means that condition for if is evaluated true even when I input valid format... any suggestions why this is happening? 我仍然收到我设置的错误消息,这意味着即使输入有效格式, if条件if被评估为真...为什么会发生这种情况的任何建议?

This script seems to work: 该脚本似乎有效:

#!/bin/bash

DATE_FORMAT="^[01][0-9][/][0-3][0-9][/][0-9][0-9][0-9][0-9]$" #MM/DD/YYYY
DATE1="$1"
DATE2="$2"

if [[ "$DATE1" =~ $DATE_FORMAT ]] && [[ "$DATE2" =~ $DATE_FORMAT ]]
then echo "Both dates ($DATE1 and $DATE2) are OK"
else echo "Please follow the valid format MM/DD/YYYY ($DATE1 or $DATE2 is wrong)."
fi

It uses the =~ operator for a positive regex match inside Bash's [[ test command . 它使用=~运算符在Bash的[[测试命令中进行正则表达式匹配]。 The documents don't mention a !~ for negative matching (though that's what Awk and Perl use). 这些文档没有提到!~否定匹配(尽管那是Awk和Perl所使用的)。 With the single-bracket [ test command, there is no regex matching. 使用单括号[ test命令时,没有正则表达式匹配。 Note that the regex expression must not be enclosed in double quotes: 请注意,正则表达式不能用双引号引起来:

Any part of the pattern may be quoted to force the quoted portion to be matched as a string. 模式的任何部分都可以加引号,以强制将引号部分匹配为字符串。 Bracket expressions in regular expressions must be treated carefully, since normal quoting characters lose their meanings between brackets. 正则表达式中的括号表达式必须小心处理,因为普通引号字符在括号之间会失去其含义。 If the pattern is stored in a shell variable, quoting the variable expansion forces the entire pattern to be matched as a string. 如果模式存储在shell变量中,则引用变量扩展将强制将整个模式作为字符串进行匹配。

The test is also more stringent, rejecting 23/45/2091 , amongst other invalid date strings. 该测试也更加严格,除了其他无效的日期字符串23/45/2091 ,还拒绝了23/45/2091

$ bash dt19.sh  11/22/2014 11/23/2014
Both dates (11/22/2014 and 11/23/2014) are OK
$ bash dt19.sh  31/22/2014 11/43/2014
Please follow the valid format MM/DD/YYYY (31/22/2014 or 11/43/2014 is wrong).
$

Corrected code: 更正的代码:

#!/bin/bash
DATE1="$1"
DATE2="$2"
if echo "$DATE1" | grep -q -E '[0-9][0-9][/][0-9][0-9][/][0-9][0-9][0-9][0-9]'
then 
    echo "Do whatever you want here"
    exit 1
else
    echo "Invalid date"
fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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