Read N lines at a time using BASH

I googled a lot; and can find many posts regarding read N lines at a time using python. While for BASH, I can hardly find any posts. (There are posts about using bash to read ONE line at a time, or line by line.)

I read the help read page, but still don't quite make sense. Don't know which option to use.

How can I read N lines at a time using bash? thx


This is harder than it looks. The problem is how to keep the file handle.

The solution is to create another, new file handle which works like stdin (file handle 0) but is independent and then read from that as you need.


# Create dummy input
for i in $(seq 1 10) ; do echo $i >> input-file.txt ; done

# Create new file handle 5
exec 5< input-file.txt

# Now you can use "<&5" to read from this file
while read line1 <&5 ; do
        read line2 <&5
        read line3 <&5
        read line4 <&5

        echo "Four lines: $line1 $line2 $line3 $line4"

# Close file handle 5
exec 5<&-

Need Your Help

Memory profiling for a daemon process

c++ eclipse memory valgrind profiler

I have a daemon process on which I want to perform a memory profile. So I took valgrind as a choice and ran it using massif tool, but since the process never dies, massif never returns the output f...

Convert Chinese characters in Percent-Encoded URI string to Chinese characters in UTF-8?

string osx utf-8 osx-snow-leopard text-manipulation

Okay, I am not sure if I am phrasing this correctly but I am given url in the following form: