Read n lines at a time using Bash

前端 未结 15 2866
难免孤独
难免孤独 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 00:53

    After having looked at all the answers, I think the following is the simplest, ie more scripters would understand it better than any other solution, but only for small number of items:

    while read -r var1 && read -r var2; do 
        echo "$var1" "$var2"
    done < yourfile.txt
    

    The multi-command approach is also excellent, but it is lesser known syntax, although still intuitive:

    while read -r var1; read -r var2; do 
        echo "$var1" "$var2"
    done < yourfile.txt
    

    It has the advantage that you don't need line continuations for larger number of items:

    while 
        read -r var1
        read -r var2
        ...
        read -r varN
    do 
        echo "$var1" "$var2"
    done < yourfile.txt
    

    The xargs answer posted is also nice in theory, but in practice processing the combined lines is not so obvious. For example one solution I came up with using this technique is:

    while read -r var1 var2; do 
        echo "$var1" "$var2"
    done <<< $(cat yourfile.txt | xargs -L 2 )
    

    but again this uses the lesser known <<< operator. However this approach has the advantage that if your script was initially

    while read -r var1; do 
        echo "$var1"
    done <<< yourfile.txt
    

    then extending it for multiple lines is somewhat natural:

    while read -r var1 var2; do 
        echo "$var1" "$var2"
    done <<< $(cat endpoints.txt | xargs -L 2 )
    

    The straightforward solution

    while read -r var1; do
        read -r var2
        echo "$var1" "$var2"
    done < yourfile.txt
    

    is the only other one that I would consider among the many given, for its simplicity, but syntactically it is not as expressive; compared to the && version or multi-command version it does not feel as right.

提交回复
热议问题