Shell – Can awk use field identifiers also for shell strings (variables)

awkshellstringvariable

Well, this apparently is not possible the way I'm trying it.

This alternate approach to obtain bar as a resulting string works, though:

#!/bin/bash

path1=/usr/tmp/foo/bar/baz

awk -F/ '{print $5}' <<< "$path1"

So far so good, but what if I want to do without the <<< operator as well as those notorious echo | ... pipes?
In a nutshell, what I'm trying to do is passing path1 as a variable with the -v pa="$path1" directive and using both the field separator -F/ and the field identifiers (e. g. $5) to parse the awkinternal pa variable, which got its value assigned from the external path1 shell variable.
Can this be done "inside" awk, too?

Best Answer

The problem with the -v option or with the var=value arguments to awk is that they can't be used for arbitrary data since ANSI C escape sequences (like \n, \b...) are expanded in them (and with GNU awk 4.2 or above, if the value starts with @/ and ends in /, it's treated as a regexp type of variable).

The alternative is to use the ARGV or ENVIRON awk arrays:

awk -F / 'BEGIN{$0 = ARGV[1]; print $5}' "$path1"

Or:

export path1
awk -F / 'BEGIN{$0 = ENVIRON["path1"]; print $5}'

Or:

path1="$path1" awk -F / 'BEGIN{$0 = ENVIRON["path1"]; print $5}'

Now, if all you want is split a shell variable, you may not need awk.

In all POSIX shells:

IFS=/; set -f
set -- $path1
printf '%s\n' "$5"
Related Question