Professional Documents
Culture Documents
Syntax:
$ awk 'BEGIN{FS="FS";}'
Awk FS is any single character or regular expression which you want to use as a
input field separator.
Awk FS can be changed any number of times, it retains its values until it is
explicitly changed. If you want to change the field separator, its better to change
before you read the line. So that change affects the line what you read.
Here is an awk FS example to read the /etc/passwd file which has “:” as field delimiter.
$ cat etc_passwd.awk
BEGIN{
FS=":";
print "Name\tUserID\tGroupID\tHomeDirectory";
print $1"\t"$3"\t"$4"\t"$6;
}
END {
gnats 41 41 /var/lib/gnats
8 Records Processed
41 41
100 101
101 102
103 7
105 111
110 116
111 117
112 119
Concatenator in the print statement “,” concatenates two parameters with a space which
is the value of awk OFS by default. So, Awk OFS value will be inserted between fields in
the output as shown below.
41=41
100=101
101=102
103=7
105=111
110=116
111=117
112=119
$cat student.txt
Jones
2143
78
84
77
Gondrol
2321
56
58
45
RinRao
2122
38
37
65
Edwin
2537
78
67
45
Dayan
2415
30
47
20
Now the below Awk script prints the Student name and Rollno from the above input file.
$cat student.awk
BEGIN {
RS="\n\n";
FS="\n";
print $1,$2;
}
$ awk -f student.awk student.txt
Jones 2143
Gondrol 2321
RinRao 2122
Edwin 2537
Dayan 2415
In the script student.awk, it reads each student detail as a single record,because awk RS
has been assigned to double new line character and each line in a record is a field, since
FS is newline character.
In the above script,each records in the file student-marks file is delimited by the
character “=”.
$ awk '{print "Processing Record - ",NR;}END {print NR, "Students Records are
processed";}' student-marks
Processing Record - 1
Processing Record - 2
Processing Record - 3
Processing Record - 4
Processing Record - 5
$cat student-marks
Jones 2143 78 84 77
Gondrol 2321 56 58 45
RinRao 2122 38 37
Edwin 2537 78 67 45
Dayan 2415 30 47
The following Awk script, prints Record(line) number, and number of fields in that
record. So It will be very simple to find out that Test3 score is missing.
1 -> 5
2 -> 5
3 -> 4
4 -> 5
5 -> 4
student-marks
student-marks
student-marks
student-marks
student-marks
In the above example, it prints the FILENAME i.e student-marks for each record of the
input file.
student-marks 1
student-marks 2
student-marks 3
student-marks 4
student-marks 5
bookdetails 1
bookdetails 2
bookdetails 3
bookdetails 4
bookdetails 5
In the above example, instead of awk FNR, if you use awk NR, for the file bookdetails
the you will get from 6 to 10 for each record.