Cleaner way to use shell variable in awk /X/,/Y/ syntax?

$ cat data
Do NOT print me
START_MARKER
Print Me
END_MARKER
Do NOT print me
$ cat awk.sh
start=START_MARKER
end=END_MARKER

echo; echo Is this ugly syntax the only way?
awk '/'"$start"'/,/'"$end"'/ { print }' data

echo; echo Is there some modification of this that would work?
awk '/$start/,/$end/ { print }' start=$start end=$end data
$ ./awk.sh

Is this ugly syntax the only way?
START_MARKER
Print Me
END_MARKER

Is there some modification of this that would work?

Can anyone advise a way to avoid the relatively ugly glommed syntax? It's really not that ugly. Just want to know if a cleaner way. Using gawk, in case that matters.

Hello, hanson44:

You can explicitly use the match operator:

awk '$0 ~ a, $0 ~ b' a='^START' b='^END' file

When you use /pat1/,/pat2/ , that's just shorthand for what my code is doing above. That shorthand however requires regular expression literals. When using the matching operator explicitly, the right-hand side can be an expression of any type. If that expression is not a regular expression literal, its string value is evaluated as a regular expression.

Regards,
Alister

1 Like

Thank you very much for explaining and clearing that up.