Search code examples
bash

Read n lines at a time using Bash


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?


Solution

  • This is harder than it looks. The problem is how to keep the file handle.

    The solution is to create another, new file handle which works like stdin (file handle 0) but is independent and then read from that as you need.

    #!/bin/bash
    
    # Create dummy input
    for i in $(seq 1 10) ; do echo $i >> input-file.txt ; done
    
    # Create new file handle 5
    exec 5< input-file.txt
    
    # Now you can use "<&5" to read from this file
    while read line1 <&5 ; do
            read line2 <&5
            read line3 <&5
            read line4 <&5
    
            echo "Four lines: $line1 $line2 $line3 $line4"
    done
    
    # Close file handle 5
    exec 5<&-