Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract string between two regexes passed as variables to awk?

Tags:

shell

unix

awk

I'm trying to extract some text in a passage that is between two strings that are being saved in variables. What is wrong with the following way?

input:

module dft ( a, b, c, clk, z, test_si, test_se );

input [7:0] a;

dft_DW_mult_uns_1 mult_31 ( .a(a), .b(b), .product(reg0) );

endmodule

output:

input [7:0] a;

dft_DW_mult_uns_1 mult_31 ( .a(a), .b(b), .product(reg0) );

using the following code:

try="module dft";

awk '/$try/{flag=1; next} /endmodule/{flag=0} flag' dft_syn.v

but it doesn't recognize the $try variable.

like image 523
UriE Avatar asked Jan 01 '26 17:01

UriE


1 Answers

You can use awk like this:

sm="module dft"
em="endmodule"

awk -v sm="$sm" -v em="$em" '$0 ~ em{p=0} p; $0 ~ sm{p=1}' file

...which property emits as output:

input [7:0] a;

dft_DW_mult_uns_1 mult_31 ( .a(a), .b(b), .product(reg0) );
  • Use -v var="value" to pass command line variables from shell to awk
  • Set and reset variable p when you encounter start or end tags
like image 133
anubhava Avatar answered Jan 05 '26 05:01

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!