awk print function in linux

Awk print function is a built-in function of awk, used for prints its arguments on the standard output (or on a file if > file or >> file is present or on a pipe if | cmd is present).

Syntax

➜  ~ awk 'pattern {  print [ expression-list ] [ > expression ] }'

Example

First, we create a test file: test.log, which is as follows:

➜  ~ cat test.log
line 1 one
line 2 two
line 3 three
line 4 four
line 5 five

Example 1, use the awk print function to print each line of the file.

➜  ~ awk '{print $0}' test.log
line 1 one
line 2 two
line 3 three
line 4 four
line 5 five

Example 2, use the awk print function to print the second field of each line of the file.

Awk uses space as delimiters by default. You can use the -F option here to specify the delimiter or not.

➜  ~ awk '{print $2}' test.log
1
2
3
4
5
➜  ~ awk -F" " '{print $2}' test.log
1
2
3
4
5

Example 3, use the awk print function to print the last field of each line of the file.

➜  ~ awk '{print $NF}' test.log
one
two
three
four
five
- NF
    number of fields in the current record.

If you clearly know the fixed number of fields per line, you can print using the variable $N.

➜  ~ awk '{print $3}' test.log
one
two
three
four
five

Example 4, use the awk print function to print specific fields on each line of the file.

➜  ~ awk '{print $1,$3}' test.log
line one
line two
line three
line four
line five

Example 5, use the awk print function to print the specified line of the file.

➜  ~ awk '{if(NR == 2 || NR == 3){print $0}}' test.log
line 2 two
line 3 three
- NR     
    ordinal number of the current record.

Example 6, use the awk print function to print the line matching the pattern.

➜  ~ awk '/line 1/{print $0}' test.log
line 1 one

Example 7, use the awk print function to print the line matching the pattern and output it to the specified file.

➜  ~ awk '/line 1/{print $0 > "out.log"}' test.log
➜  ~ cat out.log
line 1 one

Add a Comment

Your email address will not be published.