0
echo boy:foo:cheese | awk -F":" '{print $1}'

Result: boy

echo boy:foo:cheese | awk -F":" '{print $2}'

Result: foo

i=1
echo boy:foo:cheese | awk -F":" '{print $($i)}'

Result: boy:foo:cheese

Also,

 i=1
echo boy:foo:cheese | awk -F":" '{print $i}'

Result: boy:foo:cheese

I want to be able to print the ith item. The only possible reason this happens is that awk doesn't support variables for its print values? My end goal here is to loop through the string and get: boy foo cheese

2 Answers2

0

Figured it out!

echo "cat:test:cheese" | awk -F":" '{print $'$i'}'

cat

  • Not quite. This works but isn't correct. See my answer. – Etan Reisner Oct 13 '15 at 02:25
  • That, or `"{print \$$i}"`. The single quotes prevent the shell from expanding $i, so you can use double quotes, or put the $i outside the single quotes as you did. – blm Oct 13 '15 at 02:26
  • @EtanReisner "Isn't correct" is a stretch, it depends on what you want. Dan's solution works fine, as does using double quotes as I suggest or -v as you suggest. I don't think any of them are more or less correct. – blm Oct 13 '15 at 02:28
  • @blm No, directly interpolating a shell variable into an awk program is objectively not correct. Imagine if the variable was `i='0} /etc/passwd '` the awk script would print out the entirety of the `/etc/passwd` file. Now, in this context that's probably not a huge deal in reality but illustrates the point fairly clearly. – Etan Reisner Oct 13 '15 at 02:49
0

You appear to have noticed that shell variables and awk positional/field variables share a syntax $# but failed to consider that that means awk can't expand both of them.

Either the shell expands the variable or the shell does, not both.

The single quotes around the awk script mean the shell doesn't so awk does. So '{print $2}' tells awk to print the second field. Similarly for $1 telling awk to print the first field. Whereas, '{print $($i)}' tells use the awk variable i and then use that value as a positional/field variable ($<i>) and then use that as yet another positional/field variable $(<$<i>>).

Variables in awk default to 0 when uninitialized so that sequence is:

  1. $($i)
  2. $($0)
  3. $(input line)
  4. ``

which then causes awk to dutifully print nothing.

The correct way to use a shell variable is to pass it to awk using -v var="$1" and then using var in awk. Non-positional/non-field variables in awk do not use the $ sigil.

Etan Reisner
  • 77,877
  • 8
  • 106
  • 148