This is not particularly elegant, but at least this demonstrates how to use
read.
Code:
# Set IFS to just a newline
IFS='
'
reading=true
while $reading; do
# Copy file1.txt to a temporary file
cp file1.txt temp
for lines in zero one two; do
if read input; then
echo "$input" >>temp
else
# Short read -- print a diagnostic to standard error
echo "$0: reading three lines failed -- abandoning after $lines" >&2
reading=false
break
fi
done
# Run external program on temporary file
externalprogram temp
done <file2.txt
If you'd run
head -n 3 inside the loop, with standard input for the loop redirected to come from file2.txt, I suppose that would work, too. The trick is to use redirection to open the file once and then keep on reading without closing the file descriptor. Redirection (with <, or with
exec) achieves that for you.
Using a temporary file just seems like better hygiene than continuously butchering the input file, and saves you from having to keep track of how many lines exactly to remove again in case of a short read (what with the possibility of missing newlines at the end and other complications).