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?
I came up with something very similar to @albarji's answer, but more concise.
read_n() { for i in $(seq $1); do read || return; echo $REPLY; done; }
while lines="$(read_n 5)"; do
echo "========= 5 lines below ============"
echo "$lines"
done < input-file.txt
The read_n
function will read $1
lines from stdin
(use redirection to make it read from a file, just like the built-in read
command). Because the exit code from read
is maintained, you can use read_n
in a loop as the above example demonstrates.