Read n lines at a time using Bash

前端 未结 15 2791
难免孤独
难免孤独 2020-11-30 00:25

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?

15条回答
  •  北海茫月
    2020-11-30 01:02

    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.

提交回复
热议问题