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."$line" == "$2"or"$line" == "$3"is true, then the other is necessarily true also?extractis set to 1, then to the empty string. Mysedsolution is not much better, I am afraid.https://shellcheck.net, a syntax checker, or installshellchecklocally. Make usingshellcheckpart of your development process..