Bash – Read line from file then delete

bashfilesread

How can I read a series of lines from a file and then remove each line?

Obviously I can read like this:

while read -r line; do
echo $line
done < myfile.txt

But if I do this:

while read -r line; do
echo $line
sed '1d' myfile.txt
done < myfile.txt

I only get the very first line

I'm looking for an elegant way to read a line, do something with it and then remove it before moving on to the next line in the file.

Best Answer

I'd prefer to invoke sed just one time then on each line iteration. If you like to change original file you can add -i(--in-place) option to sed.

unset n
while read -r line; do
  echo $line
  : $((n++))
done < myfile.txt
sed "1,$n d" myfile.txt
Related Question