tags:

views:

225

answers:

2

Hi!

Having problems with a small awk script, Im trying to choose the newest of some log files and then use getline to read it. The problem is that it dosent work if I dont send it any input first to the script.

This works

echo | myprog.awk

this do not

myprog.awk

myprog.awk

BEGIN{
#find the newest file
command="ls -alrt | tail -1 | cut -c59-100"
command | getline logfile
close(command)
}
{
while((getline<logfile)>0){
    #do the magic 
    print $0
}
}
+1  A: 

Your problem is that while your program selects OK the logfile the block {} is to be executed for every line of the input file and you have not input file so it defaults to standard input. I don't know awk very well myself so I don't know how to change the input (if possible) from within an awk script, so I would:

#! /bin/awk -f

BEGIN{
    # find the newest file
    command = "ls -1rt | tail -1 "
    command | getline logfile
    close(command)
    while((getline<logfile)>0){
    getline<logfile
        # do the magic
        print $0
    }
}

or maybe

alias myprog.awk="awk '{print $0}'  `ls -1rt | tail -1`"

Again, this maybe a little dirty. We'll wait for a better answer. :-)

Ore
A: 

Never parse ls. See this for the reason.

Why do you need to use getline? Let awk do the work for you.

#!/bin/bash
# get the newest file
files=(*) newest=${f[0]}
for f in "${files[@]}"; do
  if [[ $f -nt $newest ]]; then
    newest=$f
  fi
done

# process it with awk
awk '{
    # do the magic
    print $0
}' $newest
Dennis Williamson
Well I wanted to do the whole thing in awk, mostly to gain some more awk experience. But thanks for the ls tip.
Your command="..." is already reaching outside awk. And as Ore stated, awk needs an input file (or stdin) - that's why you have to have the echo piped into awk.
Dennis Williamson
true about command="" but still :) So lets see if I got this right, to get out of the BEGIN section awk needs some kind of input data, sounds resonable. Ill mark Ores answer as the accepted answer.