9

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 }'
StarsSky
  • 6,721
  • 6
  • 38
  • 63
Dan-Simon Myrland
  • 327
  • 1
  • 5
  • 10

3 Answers3

15

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
devnull
  • 118,548
  • 33
  • 236
  • 227
  • this way is totally wrong way to go, should refer sed command which perreal provided. – BMW Dec 18 '13 at 02:02
  • 1
    Yeah, my actual script is bit more complex. I need to paste in suffix and prefix stuff as well. Awk therefor works well, but if my problem was isolated to this issue alone I would probably go for the sed solution. Thanks for your helpful feedback :) – Dan-Simon Myrland Jan 17 '14 at 11:13
3

Couldn't help to write this in sed:

sed 's/'"$DOCPATH"'/'"$SITEPATH"'/' input
perreal
  • 94,503
  • 21
  • 155
  • 181
1

/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.

Kevin
  • 53,822
  • 15
  • 101
  • 132