Search code examples
linuxdateawksedcut

extract header if pattern in a column matches


I am trying to extract and print header of a file if the pattern in that particular column matches.

Here is a example :

[user ~]$ cal |sed 's/July 2014//'  
Su Mo Tu We Th Fr Sa  
       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 31  

Expected output :

if input date =31 then print the day on 31st.

Just to be clear, I cannot use date -d flag as its not supported by my OS.Probably would need awk here to crack the question.

[user ~]$ date -d 20140731 +%A  
Thursday  

I hope I am able to convey my question and concern clearly.


Solution

  • Here is a gnu awk solution:

    cal | awk -v date=31 -v FIELDWIDTHS="3 3 3 3 3 3 3 3" 'NR==2 {split($0,a)} {for (i=1;i<=NF;i++) if ($i==date) print a[i]}'
    Th
    

    You set the date that you like to be displayed as a variable, so it can be change to what you like.

    Or it could be written like this:

    cal | awk 'NR==2 {split($0,a)} {for (i=1;i<=NF;i++) if ($i==date) print a[i]}' FIELDWIDTHS="3 3 3 3 3 3 3 3" date=31
    

    PS FIELDWIDTH was introduced in gnu awk 2.31