Extract lines between two patterns with awk and a

2019-07-23 14:49发布

问题:

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?

回答1:

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}"
}


回答2:

It might be simpler/clearer as:

awk -v sect="$1" '/^\[ [!-~]+ \]/{ f = ($0 ~ "^\\[ " sect " \\]") } f' file


回答3:

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