Semicolon in AWK
As in many programming languages like Java, the semicolon marks the end of one stateùent and the begin of another one. |
awke '{print $1 ; print $0}' awk.txt >>> AWK >>> AWK is awesome >>> Let >>> Let learn AWK together ...
|
The special variable FS
We can put the field separator within an AWK program vy assigning a value to the special variable FS. |
awk 'BEGIN {FS =","} {print $2}' Yellow,Blue,Red >>> Blue
|
The special variable RS
By default, AWK treats each line of its input as a separate record. But what if the input line is not devided into lines ? Let take the file OneLine.txt as an example: |
cat OneLine.txt AWK,is,awesome!Let,learn,AWK!Hello,AWK
|
In this file, fields are separated by comma and records are separated by exclamation point. Let see the following code which print the second field of each record. |
awk 'BEGIN {RS="!";FS=","} {print $2}' OneLine.txt >>> is >>> learn >>> AWK
|
|
|
OFS and ORS
AWK has also the output version of FS and RS which are respectively OFS and ORS. Let take an example using the file names.txt. |
awk 'BEGIN {OFS=",";ORS="!"} {print $1,$2}' names.txt >>> Albert,Einstein!Barak,Obama!Steve,Jobs!
|
Note that the setting of OFS has no effect on the output of $0. |
The special variable NR
NR is a special variable whose value is the record number or line number of the record that is currently being examined . |
awk '{print NR,$0}' awk.txt >>> 1 AWK is awesome >>> 2 Let learn AWK together >>> 3 AWK is used for text processing
|
If we put two input files the result will be the concatenation of the two files. |
The special variable FNR
FNR is a special variable whose value is the record number of each file. |
awk '{print FNR, $0}' names.txt awk.txt >>> 1 Albert Einstein >>> 2 Barak Obama >>> 3 Steve Jobs >>> 1 AWK is awesome >>> 2 Let learn AWK together >>> 3 AWK is used for text processing
|
|
|
The special variable FILENAME
The special variable FILENAME print the name of a file. |
awk '{print FILENAME,$0}' names.txt awk.txt >>> names.txt Albert Einshtein >>> names.txt Barak Obama >>> names.txt Steve Jobs >>> awk.txt AWK is awesome >>> awk.txt Let learn AWK together >>> awk.txt AWK is used for text processing
|
|