Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk print without a file

Tags:

awk

gawk

How to print using awk without a file.

script.sh
#!/bin/sh
for i in {2..10};do
awk '{printf("%.2f %.2f\n", '$i', '$i'*(log('$i'/('$i'-1))))}'
done

sh script.sh

Desired output
2   value
3   value
4   value
and so on

value indicates the quantity after computation

like image 463
Kay Avatar asked Nov 29 '16 07:11

Kay


3 Answers

BEGIN Block is needed if you are not providing any input to awk either by file or standard input. This block executes at the very start of awk execution even before the first file is opened.

awk 'BEGIN{printf.....

so it is like:

From man page:

Gawk executes AWK programs in the following order. First, all variable assignments specified via the -v option are performed. Next, gawk compiles the program into an internal form. Then, gawk executes the code in the BEGIN block(s) (if any), and then proceeds to read each file named in the ARGV array. If there are no files named on the command line, gawk reads the standard input.

awk structure:

 awk 'BEGIN{get initialization data from this block}{execute the logic}' optional_input_file
like image 115
P.... Avatar answered Nov 09 '22 19:11

P....


I would suggest a different approach:

seq 2 10 | awk '{printf("%.2f %.2f\n", $1, $1*(log($1/($1-1))))}'
like image 43
Michael Vehrs Avatar answered Nov 09 '22 17:11

Michael Vehrs


As PS. correctly pointed out, do use the BEGIN block to print stuff when you don't have a file to read from.

Furthermore, in your case you are looping in Bash and then calling awk on every loop. Instead, loop directly in awk:

$ awk 'BEGIN {for (i=2;i<=10;i++) print i, i*log(i/(i-1))}'
2 1.38629
3 1.2164
4 1.15073
5 1.11572
6 1.09393
7 1.07905
8 1.06825
9 1.06005
10 1.05361

Note I started the loop in 2 because otherwise i=1 would mean log(1/(1-1))=log(1/0)=log(inf).

like image 38
fedorqui 'SO stop harming' Avatar answered Nov 09 '22 18:11

fedorqui 'SO stop harming'