0

我目前正在使用这个命令,

cal $month $year | sed -n '1,2p'
cal $month $year | sed -n '3,$p' |
    sed -n '/'$day'/{s/.*\('$day'.*\)/\1/p; :a; n; p; ba; }'

它给了我这个输出

    March 2014
Su Mo Tu We Th Fr Sa
4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31

我怎样才能得到这个输出?

    March 2014
Su Mo Tu We Th Fr Sa
       4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31

仅供参考:$month $year $day正在使用当前日期。我试图避免使用一定数量的空格,因为如果它是不同的一天,那么这些数字将与空格不匹配。

编辑:乔纳森·莱弗勒

谢谢!这非常接近我正在寻找的输出。您发布的示例输出正是我正在寻找的,但在尝试了您的代码之后。它给了我这个。

March 2014 Su Mo Tu We Th Fr Sa 2 3 4 5 Q6 7 8 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

我怎样才能删除带有 Q 的线?我假设这是来自s///您提供的第二个

编辑:

想办法,谢谢你的帮助!

4

2 回答 2

2

这个脚本有效(我认为):

year=2014
month=3
day=6
cal $month $year | sed -n -e '
1,2p
3,${/'$day'/{
  s/^\(.*\)\('$day'.*\)/\1Q\2/
  :blanks
  s/^\( *\)[^ Q]/\1 /g
  t blanks
  s/Q//p
  :a
  n
  p
  ba
  }
}'

Sample output:

     March 2014       
Su Mo Tu We Th Fr Sa  
             6  7  8  
 9 10 11 12 13 14 15  
16 17 18 19 20 21 22  
23 24 25 26 27 28 29  
30 31
  • The first s/// command puts a Q (not part of the output from cal) before the day that you want to keep.
  • The label :blanks, the s/// and the t blanks replace a string of blanks and a non-blank, non-Q with the string of blanks and another blank, zapping all the non-blank characters before the Q.
  • The s/Q//p removes the marker and prints the line.
  • The remainder of the code is the same as before (but spread over multiple lines); it gets the next line of input and prints it repeatedly.
于 2014-06-04T23:57:44.933 回答
0

awk实现预期效果的脚本:

cal.awk

# Print first two lines (heading)
NR < 3 { print; next } 

# Skip weeks in which the last day is before variable 'day'
$NF < day { next }

# Print full weeks if the first day is on or after variable 'day'
$1 >= day { print; next }

# This will be executed for the week on which variable 'day' falls.
{ 
  # Traverse each day
  for (i=1; i<=NF; ++i) {
    # If current day is on or after variable 'day', print it.
    if ($i >= day) {
      if ($i < 10) # Check for extra formatting for single digit days
        printf(" ");
      printf("%d ", $i); 
    }
    else 
      printf "   "; # Formatting for blank days
  } 
  print ""; # Add new line
} 

调用:

cal $month $year | awk -v day=$day -f cal.awk
于 2014-06-04T23:57:26.443 回答