Read a file backwords line by line in bash

2020-05-07 01:47发布

问题:

I need to read my file line by line from the end. I tried tac but that works like cat and I want to access it line by line.

Is there a way to do that in bash?

回答1:

You can use tac... together with a while loop:

while IFS= read -r line
do
   echo "line is: $line"
done < <(tac file)

Test

$ seq 5 > a
$ while IFS= read -r line; do echo "line is: $line"; done < <(tac a)
line is: 5
line is: 4
line is: 3
line is: 2
line is: 1


标签: bash shell