Frage

When I try "cal | tail -6" in my unix machine, I get -

             1  2  3
 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

but when I try "cal | tail -6 | awk '{print $7}'", I get -

10
17
24

where is 3 going ? My requirement is basically all weekdays i.e column 2,3,4,5 & 6. But I'm getting wrong output because of the strange behavior of "cal"

War es hilfreich?

Lösung 2

Since all of your columns in each row are three characters wide, you could use this to extract the days you wish for. For example, if you wanted only the 7th day in a column, you could do the following:

cal | sed 's/^\(.\{18\}\).*$/\1/'

This command would remove the first 18 characters in the line, which are the entries for the first 6 days of the week.

To extract a particular day, such as the fourth day, you could do this:

cal | sed 's/^.\{9\}\(.\{3\}\).*$/\1/'

To remove the first day of the week and the last day, you could do this:

cal | sed -e 's/^.\{3\}//' -e 's/^\(.\{15\}\).\{3\}$/\1/'

Andere Tipps

There are only 3 whitespace delimited columns in your first row. cal is working exactly as corrected, you are not understanding how awk works. As far as awk is concerned there is no 7th column in your first row as it yields attention to whitespace delimited columns, not fixed width columns.

A quick google search reveals you can use

BEGIN  { FIELDWIDTHS = "3 3 3 3 3 3 3" }

In your awk script.

May be a row-wise extraction will do the trick. Try ncal. For example:

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

or fill the absent dates with place holder (with '-' for example):

kent$  cal -s|tail -6|awk 'NR==1&&NF<7{gsub(/^ */,"");for(i=1;i<=(7-NF);i++) x=" - "x;$0=x" "$0;}1'                       
 -  -  -  -  1  2  3
 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

then you could get the column, replace '-' with " " if needed. e.g. for $7:

  kent$  cal -s|tail -6|awk 'NR==1&&NF<7{gsub(/^ */,"");for(i=1;i<=(7-NF);i++) x=" - "x;$0=x" "$0;}{print $7}'   
3
10
17
24

Note that todays date is highlighted unless you turn it off (-h). Use cut to extract the wanted columns:

cal -h | cut -c19-20

Output:

Sa
 3
10
17
24
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top