1

小さな 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
}
}
4

2 に答える 2

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`" 

繰り返しますが、これは少し汚れている可能性があります。より良い回答をお待ちしております。:-)

于 2009-06-26T12:19:03.137 に答える
0

解析しないでくださいls。理由はこちらをご覧ください。

なぜ 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
于 2009-06-26T18:10:33.807 に答える