简体   繁体   中英

What is the correct syntax for nesting if-statements in awk?

I'm writing a awk command and I would like to nest if-statements using the conditional block form:

condition{actions}

instead of the one that uses the if keyword:

if(condition){actions}

This because I'm trying to use as few characters as possible.

Using the if keyword it works:

awk '{system("date +%s%N")}'|awk '{t[++b]=$1;}b>1{if(b>4)e=b-5;print int(6E10*(b-e)/(t[b]-t[e+1])),"bpm"}'

but when I try to do with the other way:

awk '{system("date +%s%N")}'|awk '{t[++b]=$1;}b>1{b>4{e=b-5;}print int(6E10*(b-e)/(t[b]-t[e+1])),"bpm"}'

I get a syntax error:

awk: lin. de com.:1: {b++;}b>1{b>4{e=b-5;}t[b]=$1;r=int(3E11/(t[b]-t[++e]));print r,"bpm"}

awk: lin. de com.:1:(......................)^ syntax error

What would be the correct syntax?

Edit: the command is for calculating how many beats per minute (bpm) a user makes when he/she presses the Enter key on the keyboard.

Input: to hit Enter key Output: how many bpm he/she did

Example -- If I hit the Enter key at a rate of ~ 115 bpm, the answer could be more or less like this:

120 bpm

112 bpm

119 bpm

122 bpm

Not sure I'm getting my point across in comments so ... consider this:

awk '{system("date +%s%N")}'

can be written as just:

date +%s%N

The other script:

{b++;}b>1{if(b>4)e=b-5;t[b]=$1;r=int(3E11/(t[b]-t[++e]));print r,"bpm"}

when written out legibly is:

{
        b++
}

b > 1 {
        if (b > 4) {
                e = b - 5
        }
        t[b] = $1
        r = int(3E11 / (t[b] - t[++e]))
        print r, "bpm"
}

which can then obviously be rewritten more briefly as:

(++b) > 4 {
        e = b - 5
}
b > 1 {
        t[b] = $1
        r = int(3E11 / (t[b] - t[++e]))
        print r, "bpm"
}

and from that there's no obvious reason for either t[b] nor r to exist since you can just write:

(++b) > 4 {
        e = b - 5
}
b > 1 {
        print int(3E11 / ($1 - t[++e])), "bpm"
}

and that can further be reduced to:

(++b) > 1 {
        e = (b > 4 ? b - 5 : e) + 1
        print int(3E11 / ($1 - t[e])), "bpm"
}

which you can then squeeze back into 1 line as you see fit. There's probably other ways to reduce the code but without an example to test against that's as far as Id want to guess at - there's probably already bugs introduced above by not having something to test against. Hopefully it gives you the idea of what you can do to reduce your code and why we need an example we can test against to be able to help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM