What does this function mean? function $$1

Viewed 90

This is the first time I've seen such usage. Unfortunately, I can't find relevant information.

awk '{print $$1}'

What's $$1 for? Is it an array?

$ echo -e "2 2 3 4\n2 22 3 4 5 6\na 2 3" | awk '{print $$1}'
2
22
a 2 3
$ echo -e "2 2 3 4\n2 22 3 4 5 6\na 2 3" | awk '{print $$2}'
2

2
$ echo -e "2 2 3 4\n2 22 3 4 5 6\na 2 3" | awk '{print $$3}'
3
3
3

The above are just examples. Note that this is not a single $, it's a $$

1 Answers

Indirect field addressing

Look at this as like this $($1).

So for second line 2 22 3 4 5 6 this command awk '{print $$1}' will look at $1 (first field). It does contain value 2, then the result will be $2 (second field) so result of $$1 will be 22. $$1 will take the number from field #1 ($1) and use this as a field number for the outer $.

Example:

$ echo -e "1 b c d\n2 b c d\n3 b c d\n4 b c d" 
1 b c d
2 b c d
3 b c d
4 b c d

Then:

$ echo -e "1 b c d\n2 b c d\n3 b c d\n4 b c d" | awk '{print $$1}'
1  # since filed #1=1 result print first field
b  # since filed #1=2 result print secondfield
c  # since filed #1=3 result print third field
d  # since filed #1=4 result print fourth field

Edit
As @kvantour points out, you can add as may $ as you like

awk '{print $$$1}' = awk '{print $$($1)}' = awk '{print $($($1))}'

And as @Ed points out, you can make it more readable by expand it like this:

awk '{print $$1}' = awk '{fieldNr=$1; print $fieldNr}'
Related