How to use field separator bultin in AWK to change field separator character ?
The default field separator in awk programming language is whitespace(\s).
We can change the field separator based on our requirements.
1. Working of default AWK field separator i.e. whitespace.
## Check out the file [root@nglinux ~]# cat /etc/hosts 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 nglinux ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 192.168.52.138 nglinux.ngelinux.com 192.168.52.136 nglinux2.ngelinux.com ### Now print first column since the second column is separated by default white-space " ". [root@nglinux ~]# cat /etc/hosts | awk '{print $1}' 127.0.0.1 ::1 192.168.52.138 192.168.52.136 [root@nglinux ~]#
2. Setting the field separator to “,” and check AWK operation.
Now lets set the field separator to a comma “,” and check its operation.
### Default uptime output [root@nglinux ~]# uptime 22:07:18 up 2 days, 1:17, 1 user, load average: 0.00, 0.00, 0.00 ### Getting number of users logged in. [root@nglinux ~]# uptime | awk -F "," '{print $3}' 1 user ### Getting load average of system [root@nglinux ~]# uptime | awk -F "," '{print $4}' load average: 0.00
Seems very easy and interesting, right !!! 🙂
3. Changing field separator to any word say “load”, “user”, etc.
We can also set the field separator to any word or any mixed sequence of characters.
Lets see it in action.
### Default uptime output. [root@nglinux ~]# uptime 22:10:05 up 2 days, 1:20, 1 user, load average: 0.00, 0.00, 0.00 ### Lets get complete load average output. [root@nglinux ~]# uptime | awk -F "user," '{print $2}' load average: 0.00, 0.00, 0.00
Again it made the task very easy, otherwise you would have out multiple command to get the above output.
4. “:” as field Separator in AWK
Lets see one more example, by changing the field separator to “:” and see its utility with passwd file.
### default /etc/passwd file. [root@nglinux ~]# tail -2 /etc/passwd luci:x:141:141:luci high availability management application:/var/lib/luci:/sbin/nologin saket:x:501:501::/home/saket:/bin/bash ### Getting only username using awk ":" as field separator. [root@nglinux ~]# tail -2 /etc/passwd | awk -F ":" '{print $1}' luci saket
AWK command is very useful, in fact a complete programming language.
We can see above, with only one option we can carry out multiple tasks on shell.