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.
#!/bin/bash # 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" done # Close file handle 5 exec 5<&-