How to connect custom bash functions with a channel

for some time now i really like the bash functions. Consider the one that calculates the average value from the nth column of the file:

avg () { awk -vc="$2" '{n+=$c;m++} END{print n/m,m}' < "$1"; } 

Is it possible to rewrite it so that it reads data from the channel? That is, to use the function in the following:

 cat data.txt | avg 
+6
source share
1 answer
 avg () { awk -vc="$1" '{n+=$c;m++} END{print n/m,m}'; } (echo 1 3; echo 2 4; echo 4 6) | avg 2 avg 2 < /tmp/file 

If you want to keep the API:

 avg () { (if [ "x$1" = "x-" ]; then cat; else cat $1; fi) | awk -vc="$2" '{n+=$c;m++} END{print n/m,m}'; } (echo 1 3; echo 2 4; echo 4 6) | avg - 2 avg /tmp/file 2 
+5
source

Source: https://habr.com/ru/post/891237/


All Articles