How do I read a file on Linux?

I know that I can use cat

to print all content from a file from start to finish on Linux. Is there a way to do this backwards (last line first)?

+3


source to share


3 answers


sed '1!G;h;$!d' file

sed -n '1!G;h;$p' file

perl -e 'print reverse <>' file

awk '{a[i++]=$0} END {for (j=i-1; j>=0;) print a[j--] }' file

      



+6


source


Yes, you can use the "tac" command.

From tac man:



Usage: tac [OPTION]... [FILE]...
Write each FILE to standard output, last line first.
With no FILE, or when FILE is -, read standard input.

Mandatory arguments to long options are mandatory for short options too.
  -b, --before             attach the separator before instead of after
  -r, --regex              interpret the separator as a regular expression
  -s, --separator=STRING   use STRING as the separator instead of newline
      --help     display this help and exit
      --version  output version information and exit

      

+9


source


tac

is one way, but not available by default on all Linux.

awk can do it like:

awk '{a[NR]=$0}END{for(i=NR;i>=1;i--)print a[i]}' file

      

+4


source







All Articles