Capturing specific sections from a file
by Faki from LinuxQuestions.org on (#5RCM2)
I have written a bash function to prints sections of text enclosed between lines matching `## mode: org` and `## # End of org` in a file, with an empty line between sections. Before the `##`, there can be any number of spaces.
Here is an example of a file to extract information from.
Code:file: test.sh
## mode: org
## * Using case statement
## # End of org
case $arg in
("V")
echo "Author"
;;
(*)
## mode: org
## ** Silent Error Reporting Mode (SERM) in getopts
## *** Detects warnings without printing built-in messages.
## *** Enabled by colon {:} as first character in shortopts.
## # End of org
break
;;
esacThe desired output would be
Code:* Using case statement
** Silent Error Reporting Mode (SERM) in getopts
*** Detects warnings without printing built-in messages.
*** Enabled by colon {:} as first character in shortopts.Here is the function I am using
Code:capture-org ()
{
sed -n '/^ *## mode: org$/,/^ *## # End of org$/s/ *//p' "$1" |
sed 's/^## mode: org$/\n## mode: org/' |
sed '/^## mode: org$/d' | sed '/^## # End of org$/d' | cut -c 3-
}It would like a neater version using variables.
I have started with the following
Code:capture-rec ()
{
local efile="$1"
local begorg="## mode: org"
local endorg="## # End of org"
sed -n '/^[[:space:]]*## mode: org$/,/^[[:space:]]*## # End of org$/s/ *//p' "$efile" |
sed 's/^## mode: org$/\n## mode: org/' |
sed '/^## mode: org$/d' | sed '/^## # End of org$/d' | cut -c 3-
}I need to use the variables begorg and endorg in the sed commands, and do need some assistance.
Here is an example of a file to extract information from.
Code:file: test.sh
## mode: org
## * Using case statement
## # End of org
case $arg in
("V")
echo "Author"
;;
(*)
## mode: org
## ** Silent Error Reporting Mode (SERM) in getopts
## *** Detects warnings without printing built-in messages.
## *** Enabled by colon {:} as first character in shortopts.
## # End of org
break
;;
esacThe desired output would be
Code:* Using case statement
** Silent Error Reporting Mode (SERM) in getopts
*** Detects warnings without printing built-in messages.
*** Enabled by colon {:} as first character in shortopts.Here is the function I am using
Code:capture-org ()
{
sed -n '/^ *## mode: org$/,/^ *## # End of org$/s/ *//p' "$1" |
sed 's/^## mode: org$/\n## mode: org/' |
sed '/^## mode: org$/d' | sed '/^## # End of org$/d' | cut -c 3-
}It would like a neater version using variables.
I have started with the following
Code:capture-rec ()
{
local efile="$1"
local begorg="## mode: org"
local endorg="## # End of org"
sed -n '/^[[:space:]]*## mode: org$/,/^[[:space:]]*## # End of org$/s/ *//p' "$efile" |
sed 's/^## mode: org$/\n## mode: org/' |
sed '/^## mode: org$/d' | sed '/^## # End of org$/d' | cut -c 3-
}I need to use the variables begorg and endorg in the sed commands, and do need some assistance.