1

We'd like to import code between two strings and put them in an variable.

We have:

job=1

listen="$(awk -v a="BEGIN-$job" -v e="END-$job" '/BEGIN {print a}/{p=1;next} /BEGIN {print e}/{p=0;exit} p' whatsthat.file)"

whatsthat.file (edited):

BEGIN-1

echo "some code"

END-1

BEGIN-2

echo "next job"

END-2

Final result for variable $listen should be:

echo "some code"

But the command above leaves $listen empty.

2
  • Of course it does not work -- it's a no-sense. What is /BEGIN {print a}/ for? Do you know what /···/ means? Commented Mar 30, 2017 at 14:44
  • E.g. if you have awk /BEGIN/{p=1;next} /END/{p=0;exit} p' whatsthat.file and only BEGIN and END in whatsthat.file it works. So the // are for checking the code between. Commented Mar 30, 2017 at 14:48

1 Answer 1

1

Your awk command has several problems, what you're looking for is this:

job=1

listen="$(
awk -v a="BEGIN-$job" -v e="END-$job" '$0==a {p=1;next} $0==e {exit} p && NF' whatsthat.file
)"
  • Patterns $0==a and $0==e check the input line at hand ($0) against the variables a and b for equality. If so, the associated action ({...}) is executed.

  • {p=1;next}, which is executed for the start of the range of interest, sets (conceptually) Boolean flag p and moves to the next input line; its purpose is to indicate that subsequent lines - due to being inside the range of interest - should (potentially) be printed.

  • {exit}, which is executed for the end of the range, unconditionally ends processing (the range-ending line, just like the range-starting one, shouldn't be printed).

  • p && NF is a pattern that tests flag p and whether the input line is nonempty (NF contains the number of whitespace-separated fields on the line, and that number is 0 for empty or blank lines); if both conditions are met, the input line at hand is implicitly printed (which is Awk's default action in the absence of an action associated with a pattern).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.