Wednesday, 1 May 2013

AWK: Remove All Blank Spaces From String / Field

I need to parse the following text file:
# example.net config
user = www30021
group = ftp30020
uid = 30021
gid = 30020
tmp_path = /netapp42/shared/www/images/host.example.com/tmp.bin
tmp_perms = defaults,nodev,nosuid,noexec
jail = on
location = /jails/apache/h/host.example.com/
sftp = on
ftps = off
php-cgi = on
perl-cgi = off

I need to find out value for each field and remove any blank spaces / white spaces from the field. 
How do I solve this problem using awk under Linux or Unix like operating systems?

Use the following syntax to to read each field and display it on the screen:
awk -F'Field-Separator-Here' '/Field-Name-Here/{ print $2}' /path/to/input/file
In this example read value for the field user, enter:
 awk -F'=' '/user/{ print "|" $2 "|"}' foo.conf
Sample outputs (note down the white space):
| www30021  |
To remove all unwanted whitespace‎s, enter:
awk -F'=' '/user/{gsub(" |\t","",print "|" $2 "|"); print $2}' filename

No comments:

Post a Comment