loop through a file 4 rows at the time and store the lines in 4 variables

I'm trying to loop through a file 4 rows at the time and store the lines in 4 variables

Source

8069347
41301052
394971301
39413010
8655766
91557668
754318656682
0279628

Desired Output stores the first 4 rows and after 5s the next 4 rows

8069347
41301052
394971301
39413010

I tried this but it only stores the line in $a and nothing $b,$c,$d

while read -r a b c d ; do
    echo "$a"
    echo "$b"
    echo "$c"
    echo "$d"
    sleep 5
done < Auto

Any idea how to fix this? I'm not opposed to a for-loop option

3 answers

  • answered 2020-07-05 01:33 John1024

    If you want to read 4 lines, you need to use the read command 4 times:

    while read -r a; read -r b; read -r c; read -r d ; do
        echo "$a"
        echo "$b"
        echo "$c"
        echo "$d"
        sleep 5
    done < Auto
    

  • answered 2020-07-05 03:57 Shawn

    You could also use bash's mapfile to populate an array 4 lines/element at a time, instead of a bunch of read's:

    while mapfile -t -n 4 lines; do
        if [[ ${#lines[@]} -eq 0 ]]; then
            break
        fi
        printf "%s\n" "${lines[@]}"
        sleep 5
    done < Auto
    

  • answered 2020-07-05 04:18 Cyrus

    With 4 read commands:

    { read -r a; read -r b; read -r c; read -r d ;} < file
    

    With a for loop and an array:

    for((i=0; i<4; i++)); do read -r array[$i]; done < file
    declare -p array
    

    Output:

    declare -a array=([0]="8069347" [1]="41301052" [2]="394971301" [3]="39413010")