On the bash shell I use the command
cat filename | cut -d, -f4 | sort -n | awk ' BEGIN { c = 0; sum = 0; } $1 ~ /^[0-9]*(\.[0-9]*)?$/ { a[c++] = $1; sum += $1; } END { ave = sum / c; if( (c % 2) == 1 ) { median = a[ int(c/2) ]; } else { median = ( a[c/2] + a[c/2-1] ) / 2; } OFS="\t"; print sum, c, ave, median, a[0], a[c-1]; } ' This works fine when run from terminal But my shell script shows awk usage when trying to use the above commands inside a script and run the script. I did
#!/bin/sh diffFile="del.csv" x=$(cat $diffFile | cut -d, -f4 | sort -n | awk 'BEGIN { c = 0; sum = 0; } $1 ~ /^[0-9]*(\.[0-9]*)?$/ { a[c++] = $1; sum += $1; } END { ave = sum / c; if( (c % 2) == 1 ) { median = a[ int(c/2) ]; } else { median = ( a[c/2] + a[c/2-1] ) / 2; } OFS="\t"; print sum, c, ave, median, a[0], a[c-1]; }' ) echo "$x" But this shows awk usage on running the script. How do I fix this.
diffFilevs.$diffFIle. I assume that's causingcatto wait for standard input, causing the freeze.x=$(cat $diffFile | cut -d, -f4 | sort -n | awk \. Otherwise, bash will think you try to invoke awk with no arguments.bashdue to easy syntax errors. the$(...)syntax does exactly the same and is more readable