Search code examples
bashawk

Using bash for loop variable within awk print


I'm trying to understand a specific situation within bash and awk:

I want to use the awk binary operator for string concatenation between two variables (a space) as the variable iterated,$i, within a bash for loop:

$ for i in ' '; do 
  echo "foo bar" | awk '{print $1$i$2}'
done
foofoo barbar

Expected output is: foobar

Question 1

  • What is going on? ANSWER (marked as correct)

Question 2

  • How can I get awk to use string concatenation as in the above bash for loop? ANSWER

Reference

$ $SHELL --version | head -n1
GNU bash, version 4.3.42(4)-release (x86_64-unknown-cygwin)

$ awk --version | head -n1
GNU Awk 4.1.3, API: 1.1 (GNU MPFR 3.1.3, GNU MP 6.1.0)

Full test

$ for i in '+' '-' '*' '/' '%' ' ' ''; do echo "2.0 4.0" | awk '{print $1$i$2}'; done
2.02.0 4.04.0
2.02.0 4.04.0
2.02.0 4.04.0
2.02.0 4.04.0
2.02.0 4.04.0
2.02.0 4.04.0
2.02.0 4.04.0

Solution

  • It seems to be a little bit tricky one. Actually it prints foo, foo bar and bar. As the value of i is not defined in (it is a variable) it is considered as $0 (I did not know this behavior, but it make sense).

    Change the code a little bit as

    for i in ' '; do 
      echo "foo bar" | awk '{print $1"<"$i">"$2}'
    done
    

    Output:

    foo<foo bar>bar
    

    If you want to pass the value of the variable i you can do using -v argument. But $i will not work as the value of i should be a number in $i, so just use simple i.

    for i in ' '; do
      echo "foo bar" | awk -v i="$i" '{print $1"<"i">"$2}'
    done
    

    Output:

    foo< >bar