[Copyright statement: reprinted. Please retain the Source: blog.csdn.net/gentleliu. Mail: shallnew at 163 dot com]
In most cases, the print statement of the awk can complete the task, but sometimes we need more. In those cases, awk provides two well-known functions: printf () and sprintf (). Yes, like many other awk components, these functions are equivalent to the corresponding C-language functions. Printf () prints the formatted string to stdout, while the sprintf () function returns the formatted string specified according to the printf format description. It formats the data but does not output the data. A w k provides the function p r I n t f, which has several different formatting output functions. For example, output by column, left or right.
The basic syntax of the printf () function is printf () ("format controller", parameter). The format control characters are usually enclosed in quotation marks. Similar to the C language, awk printf has the following formats:
% C a s c I characters
% D integer
% E floating point number, scientific notation
% F floating point number, for example (1 2 3. 4 4)
% G awk determines which floating point number to convert E or F
% O octal values
% S string
% X hexadecimal number
Try these formats below:
# echo 97 | awk '{printf("%c\n", $0)}' A
Like the C language, "\ n" is required for line feed ".
# echo 97 | awk '{printf("%d\n", $0)}'97# echo 97 | awk '{printf("%f\n", $0)}'97.000000# echo 97 | awk '{printf("%e\n", $0)}'9.700000e+01# echo 97 | awk '{printf("%s\n", $0)}'97
Formatted output similar to the C language:
# awk 'BEGIN{FS=":"}{printf("%-15s%s\n", $1, $3)}' group_file2wireshark 987usbmon 986jackuser 985vboxusers 984aln 1001
The sprintf () function returns the formatted string specified according to the printf format description. It formats data but does not output data. Therefore, you need to save the data returned by sprintf in the variable and then output it.
# awk 'BEGIN{FS=":";ORS=""}{var=sprintf("%s\n", $1);print var}' group_file2wiresharkusbmonjackuservboxusersaln
Other usage is similar to that in C.
Shell text filtering programming (5): awk printf