Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using bash for loop variable within awk print

Tags:

bash

awk

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
like image 377
adam Avatar asked Mar 06 '26 11:03

adam


1 Answers

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 awk (it is a bash 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
like image 186
TrueY Avatar answered Mar 08 '26 01:03

TrueY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!