Question

This is my script:

for i in *.locs 

do

awk -v start=$(head -n 1 ${i}) -v end=$(tail -n 1 ${i})

BEGIN {

    sum = 0;
    count = 0;
    range_start = -1;
    range_end = -1;
}
{
    irow = int($1)
    ival = $2 + 0.0
    if (irow >= start && end >= irow) {
            if (range_start == -1) {
                range_start = NR;
            }
            sum = sum + ival;
            count++;
        }
    else if (irow > end) {
            if (range_end == -1) {
                range_end = NR - 1;
            }
        }
}
END {

    echo "${i}"
    print "start =", range_start, "end =", range_end, "mean =", sum / count
}

done

Which gives me this error:

line 15: syntax error near unexpected token `}'

line 15: `}'

But when I first use the awk to generate the variables start and end followed by -f myscript.sh file

I don't get an error:

What am I missing?

Thanks in advance

No correct solution

OTHER TIPS

You need to either quote the entire awk script, or escape the dollar signs so that the shell does not expand them as positional parameters before awk is called. (Adding single quotes takes care of the other problem, which is that without a line continuation character, the awk command itself ends at the end of the line and the rest of the script is parsed as incorrect bash code):

awk -v start=$(head -n 1 ${i}) -v end=$(tail -n 1 ${i}) '

BEGIN {
...
'

Characters within your awk program are being interpreted by the shell. You can pass your program as a command-line argument to awk, but it must be enclosed in 'single-quotes' to prevent the shell from interpreting it.

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