I am writing a bash script (just learning bash) to extract some lines from a file based on two patterns. The first pattern is just a sentence ending in a colon. The second pattern is a *
repeated N (in this case 58) times.
An example file:
lines I don not want
lines I don not want
lines I don not want
A sentence here:
********************************************************
lines I want
lines I want
lines I want
**********************************************************
lines I don not want
lines I don not want
lines I don not want
Desired output:
A sentence here:
********************************************************
lines I want
lines I want
lines I want
**********************************************************
I can get the script to work if I explicitly type out A sentence here
and \*
58 times within the call to awk, but cleanliness and readability I would prefer to do something like below:
pat1="A sentence here"
pat2=`printf -- '\*%.s' {1..58} ; echo`
pat2=${pat2//\\/\\\\}
awk -v pat1="${pat1}" -v pat2="${pat2}" '/{pat1}/ {p=1}; p; /{pat2}/ {p=0}' $1
Where the first positional variable is the input file. The above code returns nothing. I initially tried it without the substitution on pat2
, but got the warning:
awk: warning: escape sequence `\*' treated as plain `*'
I will have to run this command thousands of times and would ideally like a solution that is both clean and efficient. I'm not tied to using awk
at all.
Edit:
I just noticed that even when I manually type the patterns into awk, I still receive the warning message. I am likely not passing the variables to awk correctly.
awk '/:$/,/^\*{58}$/'
. But I'm cheating. :)~
syntax in the answers you referenced, but I just triedawk -v pat1="${pat1}" -v pat2="${pat2}" '$0 ~ pat1 {p=1}; p; $0 ~ pat2 {p=0}' $1
with no luck.-v var=value
doing some backslash processing. While the other question is about doing a regexp match with an awk variable. It just so happens that one of the answers there addresses the specific issue in this question.