diff --git a/README.md b/README.md index 3462ae8..ec665e2 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,7 @@ scripts and not full blown utilities. * [Get the number of lines in a file.](#get-the-number-of-lines-in-a-file) * [Count files or directories in directory.](#count-files-or-directories-in-directory) * [Create an empty file.](#create-an-empty-file) + * [Extract lines between two markers.](#extract-lines-between-two-markers) * [File Paths](#file-paths) * [Get the directory name of a file path.](#get-the-directory-name-of-a-file-path) * [Get the base-name of a file path.](#get-the-base-name-of-a-file-path) @@ -923,6 +924,31 @@ echo -n > file printf '' > file ``` +## Extract lines between two markers. + +**Example Function:** + +```sh +extract() { + # 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" +} +``` + +**Example Usage:** + +```shell +# Extract code blocks from MarkDown file. +extract ~/projects/pure-bash/README.md '```sh' '```' +``` + + # File Paths ## Get the directory name of a file path. diff --git a/test.sh b/test.sh index 2e772bf..ca72dd3 100755 --- a/test.sh +++ b/test.sh @@ -144,6 +144,13 @@ test_get_functions() { assert_equals "${functions[0]}" "assert_equals" } +test_extract() { + printf '{\nhello, world\n}\n' > test_file + result="$(extract test_file "{" "}")" + assert_equals "$result" "hello, world" + rm test_file +} + assert_equals() { if [[ "$1" == "$2" ]]; then ((pass+=1)) @@ -161,7 +168,7 @@ main() { trap 'rm readme_code' EXIT # Extract code blocks from the README. - while read -r line; do + while IFS=$'\n' read -r line; do [[ "$code" && "$line" != \`\`\` ]] && printf '%s\n' "$line" [[ "$line" =~ ^\`\`\`sh$ ]] && code=1 [[ "$line" =~ ^\`\`\`$ ]] && code=