Ubuntu中的Awk编程

doinxwow  于 2023-10-17  发布在  其他
关注(0)|答案(3)|浏览(90)

如何在同一个awk文件中打印整个记录并请求输入(getline)?
这是awk文件的代码。它不打印输入文件中的症状列表,只在运行时询问问题。

#!/bin/awk -f
BEGIN{
print $0
printf"Enter the symptoms you are experiencing according to the numbering given in the list\n  
getline symptom<"-"
}
$1==symptom{
print $2
}

这是我的输入文件:

bvn4nwqk

bvn4nwqk1#

假设你的数据文件名为data,看起来像这样:
那么你应该能够使用this,它指定-作为两个输入文件之一,这样脚本在处理data文件后从标准输入中读取。

awk 'FNR == NR { symptom[$1] = $2; print $0; next }
    #FNR == 1  { print "Enter your symptoms by number, one per line" }
               { print $0 " ==> " symptom[$1] }' data -

如果不加注解,提示将出现在用户输入的第一行之后,而不是之前,这是一个麻烦。使用GNU Awk,您可以用途:

gawk 'FNR == NR { symptom[$1] = $2; print $0; next }
      BEGINFILE { print "Enter your symptoms by number, one per line" }
                { print $0 " ==> " symptom[$1] }' data -

BEGINFILE模式仅在第二个文件-的开始处调用。

57hvy0tb

57hvy0tb2#

$ cat file
1 Chestpainortightne    6 Triggeredbyallergens
2 HeadacheandFacialpain 7 Drycough
3 Chillswithsweating    8 Triggeredbysmoking
4 Painondeepbreathing   9 Fever
5 Coughwithsputum       10 Wheeze

$ cat tst.awk
BEGIN {
    db = ARGV[1]
    delete ARGV[1]
    ARGC--
    while ( (getline line < db) > 0 ) {
        print line
        split(line,flds)
        for (i=1;i in flds;i+=2) {
            n2v[flds[i]] = flds[i+1]
        }
    }
    close(db)
    printf "Pick a number: "
}
{
    printf "You selected %d (%s)\n", $0, n2v[$0]
    exit
}

$ awk -f tst.awk file
1 Chestpainortightne    6 Triggeredbyallergens
2 HeadacheandFacialpain 7 Drycough
3 Chillswithsweating    8 Triggeredbysmoking
4 Painondeepbreathing   9 Fever
5 Coughwithsputum       10 Wheeze
Pick a number: 2
You selected 2 (HeadacheandFacialpain)

在开始处理之前,从BEGIN部分中的数据库中阅读数据是使用getline的罕见情况之一,但在使用getline之前,请确保阅读并完全理解http://awk.info/?tip/getline中的所有警告。

unftdfkk

unftdfkk3#

awk '
    NR==FNR{ 
        for(i=1; i<=NF; i+=2) a[$i]=$(i+1)
        next 
    }
    { print }
    END{
        print ""
        while(1){
            printf "Enter the symptoms you are...: " 
            getline symptom<"-"
            if(symptom in a){
                printf "You selected %d (%s)\n", symptom, a[symptom]
                break
            }
        }
    }
' file <(sed 's/$/\n/' file|column -t)

1  Chestpainortightne     6   Triggeredbyallergens
2  HeadacheandFacialpain  7   Drycough
3  Chillswithsweating     8   Triggeredbysmoking
4  Painondeepbreathing    9   Fever
5  Coughwithsputum        10  Wheeze

Enter the symptoms you are...: 1234
Enter the symptoms you are...: foo
Enter the symptoms you are...: 5
You selected 5 (Coughwithsputum)

相关问题