0

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.

11
  • 1
    You have a small difference in capitalization when using your filename variable. diffFile vs. $diffFIle. I assume that's causing cat to wait for standard input, causing the freeze. Commented Mar 7, 2017 at 13:14
  • @jas thanks for pointing out. Now on running the script it shows awk usage :( Commented Mar 7, 2017 at 13:16
  • 3
    You need to escape the newline before the awk command, i.e. write x=$(cat $diffFile | cut -d, -f4 | sort -n | awk \ . Otherwise, bash will think you try to invoke awk with no arguments. Commented Mar 7, 2017 at 13:18
  • 2
    @VIPINKUMAR in general, backticks are strongly discouraged for bash due to easy syntax errors. the $(...) syntax does exactly the same and is more readable Commented Mar 7, 2017 at 13:22
  • 3
    Note the difference of where you put the initial single quote in the command line version that works. Do the same in the script version and you should be fine. Commented Mar 7, 2017 at 13:24

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.