Find the answer to your Linux question:
Results 1 to 5 of 5
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    [SOLVED] Problem with awk: Ignores white spaces

    Hello all !!!

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

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

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

    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
    Linux User
    Join Date
    Jan 2007
    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
    Tnx tpl for your reply.

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

    It says:

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

    Anyone has another idea ?

  4. $spacer_open
  5. #4
    Linux Guru Cabhan's Avatar
    Join Date
    Jan 2005
    Seattle, WA, USA
    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:
    echo $test | awk -F: '{print $1$2}'
    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:
    echo "$test" | awk -F: '{print $1$2}'
    This works correctly for me.

  6. #5
    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