views:

150

answers:

3

Hi I want to delete a line from a file which matches particular pattern the code I am using is

BEGIN {
       FS = "!";
       stopDate = "date +%Y%m%d%H%M%S";
       deletedLineCtr = 0;   #diagnostics counter, unused at this time
      }
      {
     if( $7 < stopDate )
          {
           deletedLineCtr++;
          }
      else
           print $0
      }

The code says that the file has lines "!" separated and 7th field is a date yyyymmddhhmmss format. The script deletes a line whose date is less than the system date. But this doesn't work. Can any one tell me the reason?

A: 

You would probably need to run the date command - maybe with backticks - to get the date into stopDate. If you printed stopDate with the code as written, it would contain "date +...", not a string of digits. That is the root cause of your problem.

Unfortunately...

I cannot find any evidence that backticks work in any version of awk (old awk, new awk, GNU awk). So, you either need to migrate the code to Perl (Perl was originally designed as an 'awk-killer' - and still includes a2p to convert awk scripts to Perl), or you need to reconsider how the date is set.

Seeing @DigitalRoss's answer, the strftime() function in gawk provides you with the formatting you want (check 'info gawk' as I did).

With that fixed, you should be getting the right lines deleted.

Jonathan Leffler
+1  A: 

Is the awk(1) assignment due Tuesday? Really, awk?? :-)

Ok, I wasn't sure exactly what you were after so I made some guesses. This awk program gets the current time of day and then removes every line in the file less than that. I left one debug print in.

BEGIN {
  FS = "!"
  stopDate = strftime("%Y%m%d%H%M%S")
  print "now: ", stopDate
}
{ if ($7 >= stopDate) print $0 }


$ cat t2.data
!!!!!!20080914233848
!!!!!!20090914233848
!!!!!!20100914233848
$ awk -f t2.awk < t2.data
now:  20090914234342
!!!!!!20100914233848
$
DigitalRoss
This requires gawk, btw, but I can do it with oawk if needed...
DigitalRoss
A: 

call date first to pass the formatted date as a parameter:

awk -F'!' -v stopdate=$( date +%Y%m%d%H%M%S ) '
    $7 < stopdate { deletedLineCtr++; next }
    {print}
    END {do something with deletedLineCrt...}
'
glenn jackman