Linux – read specified range of lines from a file

fileslinuxsed

I have i file that contains 100000 line
how i can get the lines from line# 5555 to line# 7777 under linux.

Thanks for all.

Best Answer

sed '5555,7777!d' <filename>

This will print lines 5555-7777 of the file inclusively.

Dennis Posted the following which I agree should be faster:

sed '5555,7777p; 7778q' filename

The following evidence that it should be faster:

$ n=1
$ while [[ n -le 100000 ]]; do echo $n >> sedtest2; n=$((n + 1)); done
$ strace -e trace=read -o sed1 sed '5555,7777!d' sedtest2
$ strace -e trace=read -o sed2 sed '5555,7777p; 7778q' sedtest2
$ wc -l sed1
149 sed1
$ wc -l sed2
14 sed1

In Bash only (for fun):

n=1
while read line; do 
    if [[ ($n -ge 5555) && ($n -le 7777)  ]]; then 
        echo $line
    elif [[ $n -gt 7777 ]]; then
        break
    fi 
    n=$(( $n + 1 ))
done < file