uluroki
uluroki

Reputation: 171

AWK multiple patterns substitution

Using AWK I'd like to process this text:

#replace count 12
in in
  #replace in 77
main()
{printf("%d",count+in);
}

Into:

in in
ma77()
{pr77tf("%d",12+77);
}

When a '#replace' declaration occurs, only the code below it is affected. I've got:

/#replace/ { co=$2; czym=$3 }
!/#replace/ { gsub(co,czym); print }

However I'm getting only

in in
ma77()
{pr77tf("%d",count+77);
}

in return. As you can see only the second gsub works. Is there a simple way to remeber all the substitutions?

Upvotes: 3

Views: 811

Answers (1)

Chris Seymour
Chris Seymour

Reputation: 85795

You just need to use an array to store the substitutions:

$ awk '/#replace/{a[$2]=$3;next}{for(k in a)gsub(k,a[k])}1' file
in in
ma77()
{pr77tf("%d",12+77);
}

Upvotes: 4

Related Questions