Dan-Simon Myrland
Dan-Simon Myrland

Reputation: 337

awk substitute shell variables

I am struggling with awk substitution, for some reason the following code does not substitute anything, it just prints the output unaltered. Can anyone see what I am missing here? Any help would be very much appreachiated! (PS! The $DOCPATH and $SITEPATH are shell variables, they work perfectly fine in my awk setup).

awk -v docpath="$DOCPATH" -v sitepath="$SITEPATH" '{ sub( /docpath/, sitepath ) } { print }'

Upvotes: 10

Views: 14247

Answers (3)

perreal
perreal

Reputation: 97948

Couldn't help to write this in sed:

sed 's/'"$DOCPATH"'/'"$SITEPATH"'/' input

Upvotes: 3

Kevin
Kevin

Reputation: 56089

/docpath/ will search for the literal string "docpath", not the variable as you want. Just use sub(docpath, sitepath).

N.b. if there could be multiple matches in the same line, you'll want gsub instead of sub.

Upvotes: 1

devnull
devnull

Reputation: 123508

Saying:

sub( /docpath/, sitepath )

causes awk to replace the pattern docpath, not the variable docpath.

You need to say:

awk -v docpath="$DOCPATH" -v sitepath="$SITEPATH" '{sub(docpath, sitepath)}1' filename

Upvotes: 16

Related Questions