Read n lines at a time using Bash

前端 未结 15 2825
难免孤独
难免孤独 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条回答
  •  萌比男神i
    2020-11-30 01:04

    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<&-
    

提交回复
热议问题