Reputation:
I would like to be able to read groups of lines from a file within a bash script. The following code prints the first line of a file twice
#!/bin/bash
filename=$1
read -r line < "$filename"
echo $line
read -r line < "$filename"
echo $line
whereas I would like to print the second line. The following code prints ALL lines of a file
#!/bin/bash
filename=$1
while read -r line
do
echo $line
done < "$filename"
but in a more complicated script I don't want to insert the convoluted logic to do different tasks while being forced to read every line from a file one at a time. Can someone suggest a way to do something like
# Read in a line from a file.
# Do something with that line.
#
# Read in the next 5 lines from the file.
# Do something different with those lines.
#
# etc.
Thanks.
Upvotes: 1
Views: 407
Reputation: 780724
Wrap the whole code in a block that's redirected from the file:
{
read line
// do something with $line
...
read line2
// do something with $line2
...
} < "$filename"
Upvotes: 2