Home > Back-end >  Extract lines from text file, using starting line number and amount of lines to extract, in bash?
Extract lines from text file, using starting line number and amount of lines to extract, in bash?

Time:01-16

I have seen How can I extract a predetermined range of lines from a text file on Unix? but I have a slightly different use case: I want to specify a starting line number, and a count/amount/number of lines to extract, from a text file.

So, I tried to generate a text file, and then compose an awk command to extract a count of 10 lines starting from line number 100 - but it does not work:

$ seq 1 500 > test_file.txt
$ awk 'BEGIN{s=100;e=$s 10;} NR>=$s&&NR<=$e' test_file.txt
$

So, what would be an easy approach to extract lines from a text file using a starting line number, and count of lines, in bash? (I'm ok with awk, sed, or any such tool, for instance in coreutils)

CodePudding user response:

This gives you text that is inclusive of both end points (eleven output lines, here).

$ START=100
$
$ sed -n "${START},$((START   10))p"  < test_file.txt

The -n says "no print by default".

And then the p says "print this line", for lines within the example range of 100,110

CodePudding user response:

sed -n "$Start,$End p" file

is likely a better way to get those lines.

CodePudding user response:

When you want to use awk, use something like

seq 1 500 | awk 'NR>=100 && NR<=110'

Advantage of awk is the flexibility for changing the requirements.
When you want to use a variable start and skip the endpoints, it will be

start=100
seq 1 500 | awk -v start="${start}" 'NR > start && NR < start   10'

CodePudding user response:

Another alternative with tail and head:

tail -n  $START test_file.txt | head -n $NUMBER

If test_file.txt is very large and $START and $NUMBER are small, the following variant should be the fastest:

head -n $((START NUMBER)) test_file.txt | tail -n  $START

Anyway, I prefer the sed solution noticed above for short input files:

sed -n "$START,$((START NUMBER)) p" test_file.txt 
  • Related