0

我正在尝试检查我的输入参数是模式YYYYMMDDN还是YYYYMM

如果我的日期输入是YYYYMMDDN格式,那么我需要对其进行验证并将其转换为MMNYY格式 如果我的日期输入是YYYYMM格式,那么我需要对其进行验证并将其转换为YYMM格式。

请让我知道如何做到这一点。

4

1 回答 1

0

Following will work for a date in YYYYMMDDN or YYYYMM formats:

dt='201304203'
[[ $dt =~ ^[0-9]{6}([0-9]{3})? ]] && echo "matched"

Though keep in mind that this will not validate your date.

Alternatively use sed:

echo $dt | sed -n '/^[0-9]\{6\}[0-9]\{0,3\}/p'

Alternative #2 use grep:

echo $dt | grep -qP '^[0-9]{6}[0-9]{0,3}$'

then check the return code $? (1 means failed and 0 means matched)

UPDATE:

For YYYYMMDDN => MMNYY:

echo '201304203' | sed -r 's/^[0-9]{2}([0-9]{2})([0-9]{2})[0-9]{2}([0-9])$/\2\3\1/'

For YYYYMM => YYMM:

echo '201304' | sed -r 's/^[0-9]{2}([0-9]{2})([0-9]{2})$/\1\2/'
于 2013-04-24T15:40:41.867 回答