Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7118

gawk regular expression for a pattern

I am trying to match a pattern using gawk for the following expression:

static char *nm = "This is a test with many characters like $@#^&";

The pattern is as follows:

1. Line starts with static
2. 0 or more number of characters including whitespaces
3. char
4. 0 or more number of characters including whitespaces
5. =
6. 0 or more number of characters including whitespaces
7. "
8. 0 or more number of characters including whitespaces
9. "
10. 0 or more number of characters including whitespaces
11. ;

I am trying with gawk /^static.*char.*=.*\",*\";"/{print} I am trying to insert a line containing "bbbbb" after the first matched pattern, trying as below:

   gawk '1; $1==nm1 && ++a==1 {print nm2}' nm1="^static.*char.*=.*\",*\";" nm2="bbbbb"  "aa"

If there is another occurrence of static char *nm = "This is a test with many characters like $@#^&"; this will remain as-is.

Please help.

Upvotes: 0

Views: 122

Answers (1)

anubhava
anubhava

Reputation: 784948

$1==nm1 won't apply regex as it will only perform string equality test on $1 not on whole record.

You can use this awk command:

awk -v nm2="bbbbb" '1; !p && /^static.*char.*=.*"[^"]*";/{p++; print nm2}' file

If you want to pass regex using arguments then use:

awk -v nm2="bbbbb" -v nm1='^static.*char.*=.*"[^"]*";' '1; !p && $0 ~ nm1{p++; print nm2}' file

Upvotes: 1

Related Questions