AWK: Remove All Blank Spaces From String / Field

by on April 14, 2013 · 6 comments· LAST UPDATED April 14, 2013

in , ,

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

Tutorial details
DifficultyEasy (rss)
Root privilegesNo
Requirementsawk
Estimated completion timeN/A
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
 

Sample outputs (note down the white space):

|www30021|

Final, awk statement will look as follows:

 
awk -F'=' '/user/{gsub(" |\t","",print $2 ); print $2}' filename
 
TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 6 comments… read them below or add one }

1 mdebusk April 14, 2013 at 7:39 pm

I’m just barely getting started with awk, so please pardon my ignorance.

What happens with

awk '{print $3}' filename

?

Reply

2 nixCraft April 15, 2013 at 5:52 am

Just print 3rd field. But, keep in mind the following:

## works
awk '{ print $3}' < <<'user = foo'
## fail
awk '{ print $3}' <<<'user=foo'

Reply

3 mdebusk April 15, 2013 at 1:13 pm

Ah! That makes sense. Thank you.

Reply

4 Dan April 15, 2013 at 9:31 pm

And without awk:

cut -d = -f 2 foo.conf | tr -d ” “

Reply

5 majkinetor April 17, 2013 at 5:11 am

Neither example will work correctly if there is space in the values. Trimming would be better option then replacing.

Reply

6 Jotne May 2, 2013 at 7:01 am

You have an error extra “print $2″ and no need ‘ in -F
awk -F= ‘/user/{gsub(” |\t”,”"); print $2}’

You should also point out that your input could be
user=www30021
in your example, as mdebusk pointed out.
Why all this extra, when your example is fine to go with awk ‘\user\ {print $3}’

Reply

Leave a Comment

Tagged as: , , ,

Previous Faq:

Next Faq: