Q) How to print the lines in a file in reverse order? Which means we have to print the data of file from last line to the first line.
We will see different methods to reverse the data in a file. As an example, consider the file with the below data.
We need to display the lines in a file in reverse order. The output data is
1.The tac command in unix can be used to print the file in reverse. The tac command is
2. The sed command for reversing the lines in a file is.
3. Another usage of sed command is
If you know more methods, then please comment here.
We will see different methods to reverse the data in a file. As an example, consider the file with the below data.
>cat file.txt Header line2 line3 line4 Footer
We need to display the lines in a file in reverse order. The output data is
Footer line4 line3 line2 Header
1.The tac command in unix can be used to print the file in reverse. The tac command is
tac file.txt
2. The sed command for reversing the lines in a file is.
sed '1!G;h;$!d' file.txt
3. Another usage of sed command is
sed -n '1!G;h;$p' file.txt
If you know more methods, then please comment here.
If we have a file in which data is like
ReplyDeletecol1 col2 col3
1 A B
2 W C
And we the output to be the reverse of columns i.e.
Col3 Col2 Col1
B A 1
c W 2
$ nl file | sort -nr | cut -f 2-
ReplyDeletenl commands numbers the file contents. sort sorts the numbered file in the reverse order, and the cut command removes the number and prints the file contents.
$ awk '{a[i++]=$0}END{for(j=i-1;j>=0;j--)print a[j];}' file.t xt
ReplyDelete$ perl -ne 'push @arr,$_;}{print reverse @arr;' file.txt
ReplyDeletePost a Comment