marc
marc

Reputation: 971

Issue in regex pattern matching using gawk, grep

I have a file "Input_file" with content like this

%name=ABC
%value=123
sample text in file
sample text in file
%name=XYZ
%value=789
sample text in file

I need to extract the lines of this file matching this pattern.

str="%name=*\n%value=*"

I was working this way

gawk -v st=$str '/"$st"/ {print}' $Input_file

I'm getting the error

gawk:              ^ backslash not last character on line

Even with grep as in

grep -e "$str" $Input_file

it says there is no such matching pattern. Where am I going wrong.

Upvotes: 0

Views: 229

Answers (3)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

Try this:

grep -A1 "^%name=" $Input_file | grep -B1 "^%value=" | grep -v "^--"

Upvotes: 2

Kent
Kent

Reputation: 195029

you cannot directly use your "pattern (str)" in awk. because awk default doesn't work in multi-line mode. However you could do this with awk:

 awk '/^%name=/{n=$0;next}/^%value=/&&n{print n"\n"$0}{n=""}' file

with your example, the above one-liner outputs:

%name=ABC
%value=123
%name=XYZ
%value=789

Upvotes: 1

Diego
Diego

Reputation: 46

You can use a different syntax in your $str variable, the '*' is useless in because you are searching a pattern not a literal value, for gawk I can't help sorry

try this:

str="\%name=|\%value="
egrep $str $input_file

So you can match the two criteria of you search

Upvotes: 0

Related Questions