bash – UNIX日期:如何将周数转换为日期范围(Mon-Sun)?

前端之家收集整理的这篇文章主要介绍了bash – UNIX日期:如何将周数转换为日期范围(Mon-Sun)?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有从大日志文件提取的周数列表,它们是使用语法提取的:
$date --date="Wed Mar 20 10:19:56 2012" +%W;
12

我想创建一个简单的bash函数,可以将这些周数转换为日期范围.我想函数应该接受2个参数:$number和$year,例如:

$week() { ......... }
$number=12; year=2012
$week $number $year
"Mon Mar 19 2012" - "Sun Mar 25 2012"
使用GNU日期:
$cat weekof.sh
function weekof()
{
    local week=$1 year=$2
    local week_num_of_Jan_1 week_day_of_Jan_1
    local first_Mon
    local date_fmt="+%a %b %d %Y"
    local mon sun

    week_num_of_Jan_1=$(date -d $year-01-01 +%W)
    week_day_of_Jan_1=$(date -d $year-01-01 +%u)

    if ((week_num_of_Jan_1)); then
        first_Mon=$year-01-01
    else
        first_Mon=$year-01-$((01 + (7 - week_day_of_Jan_1 + 1) ))
    fi

    mon=$(date -d "$first_Mon +$((week - 1)) week" "$date_fmt")
    sun=$(date -d "$first_Mon +$((week - 1)) week + 6 day" "$date_fmt")
    echo "\"$mon\" - \"$sun\""
}

weekof $1 $2
$bash weekof.sh 12 2012
"Mon Mar 19 2012" - "Sun Mar 25 2012"
$bash weekof.sh 1 2018
"Mon Jan 01 2018" - "Sun Jan 07 2018"
$
原文链接:https://www.f2er.com/bash/384347.html

猜你在找的Bash相关文章