≡ Menu

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

Sample outputs (note down the white space):


Final, awk statement will look as follows:

awk -F'=' '/user/{gsub(" |\t","",print $2 ); print $2}' filename
Share this tutorial on:

Like this? Follow us on Twitter OR support us by using Patreon

{ 6 comments… add one }
  • mdebusk April 14, 2013, 7:39 pm

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

    What happens with

    awk '{print $3}' filename


    • nixCraft April 15, 2013, 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'
  • mdebusk April 15, 2013, 1:13 pm

    Ah! That makes sense. Thank you.

  • Dan April 15, 2013, 9:31 pm

    And without awk:

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

  • majkinetor April 17, 2013, 5:11 am

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

  • Jotne May 2, 2013, 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
    in your example, as mdebusk pointed out.
    Why all this extra, when your example is fine to go with awk ‘\user\ {print $3}’

Security: Are you a robot or human?

Leave a Comment

You can use these HTML tags and attributes: <strong> <em> <pre> <code> <a href="" title="">

   Tagged with: , , ,