Extract lines between two patterns with awk and a variable regex

允我心安 提交于 2019-12-24 01:46:07

问题


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


来源:https://stackoverflow.com/questions/24779667/extract-lines-between-two-patterns-with-awk-and-a-variable-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!