How to read a file backwards on Linux?

10,709

Solution 1

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

Solution 2

Yes, you can use "tac" command.

From man tac:

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

Solution 3

tac is one way, but not default available on all linux.

awk could do it like:

awk '{a[NR]=$0}END{for(i=NR;i>=1;i--)print a[i]}' file
Share:
10,709
Pedro Alves
Author by

Pedro Alves

Bachelor's degree in Applied mathematics from Universidade de Campinas(2013), MSc (2016) and currently a PhD student in Compute science at the same university. His research is focused on information security, specifically cryptography and homomorphic encryption, and high performance computing. He has strong experience with parallel programming using CUDA and common parallel libraries for CPU such as PThreads, OpenMP and MPI. Moreover, has works in geophysics and biology on the development of specialized software using CUDA platform.

Updated on June 24, 2022

Comments

  • Pedro Alves
    Pedro Alves almost 2 years

    I know that I can use cat to print all content from a file from beginning to end on Linux. Is there a way for doing that backward (last line first)?

    • Paul Turner
      Paul Turner about 11 years
      What do you mean by "read"? Be specific about the content of the file and what you expect a "backwards" result to look like.
    • bobef
      bobef almost 10 years
      I wanted to look at the end of 2gb file, all 2gb on a single line, so I did this "dd if=file.xml ibs=1 skip=2049186000 count=100" - meaning to read 100 bytes starting from position 2049186000. The output has some dd stuff in it but it does the job.