Ranieri Mazili
Ranieri Mazili

Reputation: 833

How to replace part of awk command by a variable?

I have the following awk command that works...

awk 'BEGIN{RS="</a>"; ORS=RS"\n"} /<p>Test2<\/p>/' file

But now I need to replace Test2 by a shell script variable.

I've tried using -v option like below, but without success

awk -v ss="Test2" 'BEGIN{RS="</a>"; ORS=RS"\n"} /<p>{print ss}<\/p>/' file

As I told above, I'm using this command in a script, so I've tried to replace using directly my script variable, without success too...

AWK_SEARCH="Test2"
awk 'BEGIN{RS="</a>"; ORS=RS"\n"} /<p>${AWK_SEARCH}<\/p>/' file

I really appreciate any help.

Upvotes: 1

Views: 979

Answers (3)

Ed Morton
Ed Morton

Reputation: 204731

awk -v tgt="Test2" 'BEGIN{RS="</a>"; ORS=RS"\n"; tgt="<p>"tgt"</p>"} $0 ~ tgt' file

Modifying the variable in the BEGIN section is much more efficient than concatenating then testing the string once per input line.

Upvotes: 2

mikero
mikero

Reputation: 134

You need to 'unquote' your script variable:

#!/bin/bash
AWK_SEARCH="Test2"
awk 'BEGIN{RS="</a>"; ORS=RS"\n"} /<p>'"${AWK_SEARCH}"'<\/p>/' file

It's 'stopping' the awk quotes right before the script variable, enclosing the script variable in double quotes, and then 'continuing' the awk quotes right after the script variable (at least that's how I think of it).

Upvotes: 0

sjsam
sjsam

Reputation: 21975

This might be what you're looking for :

 var="test2"; #dynamic content, you can set it to "$1" and pass the value as 
 #argument to script
 awk -v awk_var="$var" '
 BEGIN{RS="</a>"; ORS=RS"\n"}
 $0 ~ "<p>"awk_var"</p>"' 37095194.txt 

Upvotes: 3

Related Questions