Awk基本入门[6] Additional Awk Commands 1

1、Pretty Printing Using printf


Syntax:

printf "print format", variable1, variable2, etc.

Special Characters in the printf Format

The following prints "Line 1" and "Line 2" in separate lines using newline:

$ awk 'BEGIN { printf "Line 1
Line 2
" }'
Line 1
Line 2

The following prints different fields separated by tabs, with 2 tabs after "Field 1":

$ awk 'BEGIN 
{ printf "Field 1		Field 2	Field 3	Field 4
" }'
Field 1        Field 2    Field 3    Field 4

The following prints vertical tabs after every field:

$ awk 'BEGIN { printf "Field 1vField 2vField 3vField 4
" }'
Field 1
       Field 2
              Field 3
                     Field 4

The following prints a backspace after every field except Field4. This erases the last number in each of the first three fields.

$ awk 'BEGIN 
{ printf "Field 1Field 2Field 3Field 4
" }'
Field Field Field Field 4

In the following example, after printing every field, we do a "Carriage Return" and print the next value on top of the current printed value.

$ awk 'BEGIN 
{ printf "Field 1
Field 2
Field 3
Field 4
" }'
Field 4

Printf Format Specifiers

The following example shows the basic usage of the format specifiers:

$ cat printf-format.awk
BEGIN {
printf "s--> %s
", "String"
printf "c--> %c
", "String"
printf "s--> %s
", 101.23
printf "d--> %d
", 101.23
printf "e--> %e
", 101.23
printf "f--> %f
", 101.23
printf "g--> %g
", 101.23
printf "o--> %o
", 0x8
printf "x--> %x
", 16
printf "percentage--> %%
", 17
}
$ awk -f printf-format.awk
s--> String
c--> S
s--> 101.23
d--> 101
e--> 1.012300e+02
f--> 101.230000
g--> 101.23
o--> 10
x--> 10
percentage--> %

Print with Fixed Column Width (Basic)

To create a fixed column width report, you have to specify a number immediately after the % in the format specifier. This number indicates the minimum number of character to be printed. When the input-string is smaller than the specified number, spaces are added to the left to make it fixed width.

Spaces are added to the left to print “Good” as a 6 character string:

$ awk 'BEGIN { printf "|%6s|
", "Good" }'
|  Good|

The whole string is printed here even though you specified 6 character

$awk 'BEGIN { printf "|%6s|
", "Good Boy!" }'
|Good Boy!|

Print with Fixed Width (Left Justified)

When the input-string is less than the number of characters specified, and you would like it to be left justified (by adding spaces to the right), use a minus symbol (-) immediately after the % and before the number.

"%-6s" is left justified as shown below:

$ awk 'BEGIN { printf "|%-6s|
", "Good" }'
|Good  |

Print with Leading Zeros

For right justified with 0's in front of the number (instead of the space), add a zero (0) before the number. i.e. Instead of "%5s", use "%05s" as the format identifier.

$ awk 'BEGIN { printf "|%05s|
", "100" }'
|00100|

Print Absolute Fixed Width String Value

To print maximum of ONLY 6 characters, add a decimal before the number. i.e. Instead of "%6s", give "%.6s", which will print only 6 characters from the input string, even when the input string is longer than that as shown below.

$ awk 'BEGIN { printf "%.6s
", "Good Boy!" }'
Good B

Dot . Precision

A dot before the number in format identifier indicates the precision.

This example shows how the number "101.23" is printed differently when using using .1 and .4 (using d, e, f, and g format specifier).

$ cat dot.awk
BEGIN {
print "----Using .1----"
printf ".1d--> %.1d
", 101.23
printf ".1e--> %.1e
", 101.23
printf ".1f--> %.1f
", 101.23
printf ".1g--> %.1g
", 101.23
print "----Using .4----"
printf ".4d--> %.4d
", 101.23
printf ".4e--> %.4e
", 101.23
printf ".4f--> %.4f
", 101.23
printf ".4g--> %.4g
", 101.23
}

$ awk -f dot.awk
----Using .1----
.1d--> 101
.1e--> 1.0e+02
.1f--> 101.2
.1g--> 1e+02
----Using .4----
.4d--> 0101
.4e--> 1.0123e+02
.4f--> 101.2300
.4g--> 101.2

Print Report to File

You can redirect the output of a print statement to a specific output file inside the awk script. In the following example the 1st print statement has "> report.txt", which creates the report.txt file and sends the output of the prints statement to it. All the subsequent
print statements have ">> report.txt", which appends the output to the existing report.txt file.

$ cat printf-width4.awk
BEGIN {
FS=","
printf "%-3s	%-10s	%-10s	%-5s	%-3s
",
"Num","Description","Type","Price","Qty" > "report.txt"
printf
"-----------------------------------------------------
n" >> "report.txt"
}
{
if ($5 > 10)
printf "%-3d	%-10s	%-10s	$%-.2f	%03d
",
$1,$2,$3,$4,$5 >> "report.txt"
}
$ awk -f printf-width4.awk items.txt

$ cat report.txt
Num
Description
Type
Price
Qty
-------------------------------------------------
103 MP3 Player
Audio
104 
$270.00 015
Tennis Racket Sports
$190.00 020

2、Built-in Numeric Functions


Awk int(n) Function

n is any number with or
with out floating point. If you give a whole number as an argument, this function returns the same number; for a floating point number, it truncates.

Init Function Example:

$ awk 'BEGIN{
print int(3.534);
print int(4);
print int(-5.223);
print int(-5);
}'

3
4
-5
-5

The above command produces the following output.

 Awk log(n) Function

The log(n) function provides the natural logarithm of given argument n. The number n must be positive, or an error will be thrown.

Awk sqrt(n) Function

sqrt function gives the positive square root for the given integer n.This function also requires a positive number, and it returns nan error if you give the negative number as an argument.

Awk exp(n) Function

The exp(n) function provides e to the power of n.

Awk sin(n) Function

The sin(n) function gives the sine of n, with n in radians.

Awk cos(n) Function

The cos(n) returns the cosine of n, with n in radians.

Awk atan2(m,n) Function

This function gives you the arc-tangent of m/n in radians.

3、Random Number Generator


 

Awk rand() Function

rand() is used to generate a random number between 0 and 1. It never returns 0 or 1, always a value between 0 and 1. Numbers are random within one awk  run, but predictable from run to run.

The following example generates 1000 random numbers between 0 and 100, and shows how often each number was generated.

$ cat rand.awk
BEGIN {
while(i<1000)
{
    n = int(rand()*100);
    rnd[n]++;
    i++;
}
for(i=0;i<=100;i++) {
    print i,"Occured", rnd[i], "times";
}
}


$ awk -f rand.awk
0 Occured 6 times
1 Occured 16 times
2 Occured 12 times
3 Occured 6 times
4 Occured 13 times
5 Occured 13 times
6 Occured 8 times
7 Occured 7 times
8 Occured 16 times
9 Occured 9 times
10 Occured 6 times
11 Occured 9 times
12 Occured 17 times
13 Occured 12 times

From the above output, we can see that the rand() function can generate repeatable numbers very often.

Awk srand(n) Function

srand(n) is used to initialize the random number generation with a given argument n. Whenever program execution starts, awk starts generating its random  numbers from n. If no argument were given, awk would use the time of the day to generate the seed.

原文地址:https://www.cnblogs.com/yangfengtao/p/3194437.html