bashshellsed

Extract lines between two line numbers in shell


How is this possible in shell using sed or any other filter

Lets say that i have two specific line numbers in two variables $line1 and $line2 and i want to extract lines between these two lines like this

cat my_file_path | command $line1 $line2

Example if my file is:

1:bbb
2:cccc
3:dddd
4:eeeee

My output should be if i do:

cat my_file_path | command 1 3

Output

bbb
cccc

Solution

  • without testing:

    awk -v s="$line1" -v e="$line2" 'NR>s&&NR<e' file
    

    you can control the "inclusive/exclusive" with >= or <=

    if you want to make it safe for leading/trailing spaces in your shell var:

     awk -v s="$line1" -v e="$line2" 'NR>1*s&&NR<1*e' file