Read n lines at a time using Bash

前端 未结 15 2614
难免孤独
难免孤独 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:08

    to read n+2 Lines from a file:-

    2

    4

    6

    8

    .

    .

    so on

    you can try this way:-

    cat fileName | awk '!((NR - 0) % 2)'

    0 讨论(0)
  • 2020-11-30 01:14

    I don't think there is a way to do it natively in bash, but one can create a convenient function for doing so:

    #
    # Reads N lines from input, keeping further lines in the input.
    #
    # Arguments:
    #   $1: number N of lines to read.
    #
    # Return code:
    #   0 if at least one line was read.
    #   1 if input is empty.
    #
    function readlines () {
        local N="$1"
        local line
        local rc="1"
    
        # Read at most N lines
        for i in $(seq 1 $N)
        do
            # Try reading a single line
            read line
            if [ $? -eq 0 ]
            then
                # Output line
                echo $line
                rc="0"
            else
                break
            fi
        done
    
        # Return 1 if no lines where read
        return $rc
    }
    

    With this one can easily loop over N-line chunks of the data by doing something like

    while chunk=$(readlines 10)
    do
        echo "$chunk" | ... # Whatever processing
    done
    

    In this loop $chunk will contain 10 input lines at each iteration, except for the last one, which will contain the last lines of input, which might be less than 10 but always more than 0.

    0 讨论(0)
  • 2020-11-30 01:14

    The echo simulates a file with two lines input, use head -2 before paste if needed:

    IFS=\; read A B < <(echo -en "X1 X2\nY1 Y2\n" | paste -s -d\;)
    

    If you want to read lines in a loop and create pairs and lines have only single word in them use:

    while read NAME VALUE; do 
        echo "$NAME=$VALUE"; 
    done < <(echo -en "M\n1\nN\n2\nO\n3\n" | xargs -L2 echo)
    
    0 讨论(0)
提交回复
热议问题