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
$ $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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With