Question

This works:

awk -F2 '{if (NF > 1) { if (substr($1,0,2) == "..") printf ("%.2f 2%s", ((50*length($1))/1000) , $2); else printf("%s2%s",$1,$2); for (i=3;i<=NF;i++) printf("2%s",$i) } else if (substr($1,0,2) == "..") printf("%.2f",((50*length($1))/1000)); else printf("%s",$1); printf("\n");}'-f debugconsole > debugconsoleWithCount 

But when I make the file countdots.awk as follows:

BEGIN {
    if (NF > 1) 
    { 
        if (substr($1,0,2) == "..") 
            printf ("%.2f 2%s", ((50*length($1))/1000) , $2);
        else 
            printf("%s2%s",$1,$2)
        for (i=3;i<=NF;i++) 
            printf("2%s",$i) 
    } 
    else 
        if (substr($1,0,2) == "..") 
        printf("%.2f",((50*length($1))/1000)); 
    else printf("%s",$1); 
        printf("\n");
}

and run it like this:

awk -F2 -f countdots4.awk debugconsole > debugconsoleWithCount

I get an empty debugconsoleWithCount file.

Was it helpful?

Solution

A BEGIN block in awk is executed only once, before the first input record is read.

An END rule is executed only once, after all the input is read.

In your transformation, since you put everything in BEGIN block, it becomes a no-op since values of NF, $1, $2 .. etc is not even set. Hence you get an empty file. If you remove it it should work fine.

BEGIN and END blocks are not mandatory so you don't have to keep them in your awk script. BEGIN is often used to print titles, headers, initializing variables to particular values etc. END block is often used to do final processing after entire input is read.

OTHER TIPS

Basically this has to do with not understanding BEGIN and END.

I took out BEGIN and it does what I want.

Should I delete this from stackoverflow? let me know.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top