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 awk
–internal 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 thevar=value
arguments toawk
is that they can't be used for arbitrary data since ANSI C escape sequences (like\n
,\b
...) are expanded in them (and with GNUawk
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
orENVIRON
awk
arrays:Or:
Or:
Now, if all you want is split a shell variable, you may not need
awk
.In all POSIX shells: