[Code Example] Get content between two substrings using bash script


To get the content between two substrings, we will provide you a bash script code. You will need to provide a file from which you want to extract the content and two substring markers to match the ends.

Code Example –


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"

Suppose you have a text file – myfile.txt with this content –

This is the first line <>
This text will be extracted
This is the last line

Extracting text between <> and </>

extract ~/Downloads/myfile.txt '<>' '</>'

Output –

This text will be extracted

Inspired from Dylan Araps

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like