Ben Chuanlong Du's Blog

And let it direct your passion with reason.

Print Rows from a Text File

It is suggested that you use Python instead of Shell to manipulate text files!

Please refer to Advanced Use of "head" and "tail" on how to use head and tail for printing rows from a text file. These 2 commands are convenient when you want to take head/tail rows. If you want to take middle rows of a file, better ways exists using sed and awk.

# print lines 10 to 20 using sed
sed -n '10,20p' filename
# print lines 10 to 20 using awk
awk 'NR >= 10 && NR <= 20' file_name

If you work with a very large file, you make the sed command a little bit more efficient by quitting ealier. For example, the following command efficiently prints lines 10000000 to 10000020 of the file.

sed -n '10000000,10000020p; 10000021q' file_name 

Thi way is faster than awk (but slower without the quitting early trick) on large files.

Comments