2

I'm searching for a way to extract the lines between two patterns with awk with the use of variables. Each section ends where the next one starts.

Example file:

[ SECTION_1 ]
info 1
info 2
info 3
[ SECTION_2 ]
info 4
info 5
info 6
[ SOMETHING_SOMETHING_DARK_SIDE ]
...
[ WE_have_COokIES ]

with

awk '/^\[ SECTION_1 \]/{p=1;next} /^\[ [!-~]+ \]/{p=0} p' "${MY_FILE_PATH}"

I get what I want:

info 1
info 2
info 3

But I would like to have something like this:

function get { 
  awk '/^\[ "$1" \]/{p=1;next} /^\[ [!-~]+ \]/{p=0} p' "${MY_FILE_PATH}"
}

Nothing seems to work :( Any ideas or hints?

nTOXIC
  • 143
  • 2
  • 12

3 Answers3

2

You're quoting it wrong with double quotes. Positional parameter $1 is not expanded in since it's still enclosed in single quotes. It should be:

function get { 
    awk '/^\[ '"$1"' \]/{p=1;next} /^\[ [!-~]+ \]/{p=0} f' "${MY_FILE_PATH}"
}

Perhaps another good way is to use -v. At least critical syntax errors may be avoided:

function get { 
    awk -v s="$1" '$0 ~ "^\\[ " s " \\]"{p=1;next} /^\[ [!-~]+ \]/{p=0} f' "${MY_FILE_PATH}"
}
konsolebox
  • 72,135
  • 12
  • 99
  • 105
  • Never use that first approach as it is full of caveats and potential bugs. The second one is close but you need to double-escape RE meta-characters withing string literals - as written `\[` is the same as `[`, you need `\\[`. – Ed Morton Jul 16 '14 at 14:05
  • 1
    @EdMorton Yes you're correct. I missed quoting that. – konsolebox Jul 16 '14 at 14:18
0

It might be simpler/clearer as:

awk -v sect="$1" '/^\[ [!-~]+ \]/{ f = ($0 ~ "^\\[ " sect " \\]") } f' file
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
-1

Here you have an entirely different approach using sed; It first uses a regular expression the get rid of the lines starting with [
and than it removes the empty lines.

$ sed 's/^\[.*//g' sections.txt | sed '/^$/d'
info 1
info 2
info 3
info 4
info 5
info 6
Kokkie
  • 546
  • 6
  • 15
  • 2
    ..., but that does not meet the requirements to get the content of the specified section itself. – nTOXIC Jul 16 '14 at 12:12