Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read lines between two lines specified by their line number

Tags:

bash

shell

How would I go about reading all lines between two specific lines?

Lets say line 23 is where I want to start, and line 56 is the last line to read, but it is not the end of the file.

How would I go about reading lines 23 thru 56? I will be outputting them to another file.

like image 483
Anthony Miller Avatar asked Feb 10 '12 21:02

Anthony Miller


2 Answers

By row number like that is quite easy with awk:

awk 'NR >= 23 && NR <= 56'

And either way, sed makes it fun.

sed '23,56!d'

Or for a pattern,

sed '/start/,/end/!d'
like image 87
Kevin Avatar answered Oct 12 '22 13:10

Kevin


I would go for sed, but a head/tail combination is possible as well:

head -n 56 file | tail -n $((56-23)) 

Well - I'm pretty sure there is an off-by-one-error inside. I'm going to find it. :)

Update:

Haha - know your errors, I found it:

head -n 56 file | tail -n $((56-23+1)) 
like image 43
user unknown Avatar answered Oct 12 '22 11:10

user unknown