So, a while ago I saw this snippet for extracting text between two "markers":
# Usage: extract file "opening marker" "closing marker"
while IFS=$'\n' read -r line; do
[[ "$extract" && "$line" != "$3" ]] &&
printf '%s\n' "$line"
[[ "$line" == "$2" ]] && extract=1
[[ "$line" == "$3" ]] && extract=
done < "$1"
(Here i just took the liberty to remove it from the function and put it in a file called extract
)
Now, it does work fine on "most" pair of markers. But i noticed it doesn't always work:
Following the original snippet's example, using N repeated char (using "#" instead of "`" because of formatting error on SO):
###sh
test
###
works when doing extract file '###sh' '###'
but if we use the following marker:
###
test
###
and do extract file '###' '###'
, then it doesn't work?
Though i can see that the condition in the script does evaluate correctly (the extract
variable being equal to 1
when using set -x
).
What's wrong here?
PS: By saying "It doesn't work", I do mean that it doesn't print anything in the instance when it doesn't work, of course.
The two example output above shouldn't contain the markers (just the texts extracted between two markers)...
I prefer a bash/shell solution if possible.
sed -n "/$2/,/$3/p" $1
, although a bit more work is required if the markers contain quotes or slashes. – berndbausch May 08 '21 at 23:25"$line" == "$2"
or"$line" == "$3"
is true, then the other is necessarily true also? – steeldriver May 08 '21 at 23:32extract
is set to 1, then to the empty string. Mysed
solution is not much better, I am afraid. – berndbausch May 08 '21 at 23:32sed
works (I had not expected this) but also prints the markers (which should have been expected). – berndbausch May 08 '21 at 23:36extract
:[[ extract=="" && "$line" == $2 ]]
or so. – berndbausch May 08 '21 at 23:37https://shellcheck.net
, a syntax checker, or installshellcheck
locally. Make usingshellcheck
part of your development process.. – waltinator May 08 '21 at 23:46while read
loop. See Why is using a shell loop to process text considered bad practice? – cas May 09 '21 at 05:45