Find the answer to your Linux question:
Results 1 to 5 of 5
Hello all !!! I have a problem with awk ignoring blanks. Consider the following example: Code: export test="aa a:bbb:ccc:ddd" Now using echo and awk I want to print the first ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Dec 2010
    Posts
    3

    [SOLVED] Problem with awk: Ignores white spaces


    Hello all !!!

    I have a problem with awk ignoring blanks. Consider the following example:

    Code:
    export test="aa                 a:bbb:ccc:ddd"
    Now using echo and awk I want to print the first two elements by parsing on ":"

    Code:
    echo $test | awk -F: {'print $1$2'}
    The output is as follows:

    Code:
    aa abbb
    As you notice a lot of white spaces has not been restituted !!!!

    I absolutly need those white spaces to be printed. Does anyone have a solution to this ?

  2. #2
    tpl
    tpl is offline
    Linux User
    Join Date
    Jan 2007
    Location
    cleveland
    Posts
    477
    welcome to the forum

    try with slightly different syntax in the awk comand

    awk -F: '{print $1$2}' <test

    this preserves whitespace
    the sun is new every day (heraclitus)

  3. #3
    Just Joined!
    Join Date
    Dec 2010
    Posts
    3
    Tnx tpl for your reply.

    The redirection dosn't work neither in bash nor in ksh.

    It says:

    Code:
    bash: $test: ambiguous redirect
    Moreover, I need to use this in a ksh script.

    Anyone has another idea ?

  4. #4
    Linux Guru Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,252
    Such redirection would only work if "test" were a file, not a variable.

    However, that is not the problem.

    The problem here actually has to do with echo, not awk. You see, Bash scripting is very stupid. It just literally replace variables. So this line:
    Code:
    echo $test | awk -F: '{print $1$2}'
    becomes:
    Code:
    echo aa       a:bbb:ccc:ddd | awk -F: '{print $1$2}'
    echo separates its arguments by any amount of whitespace, so it is literally printing "aa a:bbb:ccc:ddd".

    To get around this problem (and as a general rule), always surround variables in quotes in Bash:
    Code:
    echo "$test" | awk -F: '{print $1$2}'
    This works correctly for me.

  5. #5
    Just Joined!
    Join Date
    Dec 2010
    Posts
    3
    Thank you very much Cabhan !!!!

    That was the simple trick I was looking for. That solved the problem.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •