选择最新的文件并使用getline来阅读它

时间:2009-06-26 09:13:58

标签: awk

有一个小的awk脚本问题,我试图选择最新的一些日志文件,然后使用getline来读取它。问题是,如果我不先将任何输入发送到脚本,它就会起作用。

这有效

echo | myprog.awk

这不

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
}
}

2 个答案:

答案 0 :(得分:1)

您的问题是,当您的程序选择OK时,日志文件将为输入文件的每一行执行块{},而您没有输入文件,因此它默认为标准输入。我自己也不太熟悉awk所以我不知道如何在awk脚本中更改输入(如果可能),所以我会:

#! /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
    }
}

或者

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

同样,这可能有点脏。我们会等待更好的答案。 : - )

答案 1 :(得分:0)

永远不要解析ls。请参阅this了解原因。

为什么需要使用getline?让awk为您完成工作。

#!/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
相关问题