Thursday, March 1, 2012

15 different ways to display the contents of a file



  Looking at the file contents is one such activity which a UNIX developer might be doing in sleep also. In this article, we will see the umpteen different ways in which we can display or print the contents of a file.

Let us consider a file named "a", with the following  contents:
a
b
c
1. The first is the most common cat command:
$ cat a
a
b
c

Another variant of "cat " will be:
cat < a
2. paste command, we might have used it earlier, to paste contents from multiple files. But, when paste is used without any options against a single file, it does print out the contents.
$ paste a
a
b
c
3. grep command, as we know, will search for the text or regular expression in a file. What if, our regular expression, tells to match anything(.*). Of course, the whole file comes out.
$ grep '.*' a
a
b
c
4. The good old cut command. "1-"  indicates from 1st column till the end, in other words, cut and display the entire file.
$ cut -c 1- a
a
b
c 
5. Using the famous while loop of the shell:
$ while read line
>do
> echo $line
>done < a
a
b
c
6. xargs command. xargs takes input from standard input. By default, it suppresses the newline character. -L1 option is to retain the newline after every(1) line.
$ xargs -L1 < a
a
b
c
7. sed without any command inside the single quote just prints the file.
$ sed '' a
a
b
c
8. sed' s -n option is to supress the default printing. And 'p' is to print. So, we supress the default print, and print every line explicitly.
$ sed -n 'p' a
a
b
c
9. Even more explicit. 1,$p tells to print the lines starting from 1 till the end of the file.
$ sed -n '1,$p' a
a
b
c
10. awk solution. 1 means true which is to print by default. Hence, every line encountered by awk is simply printed.
$ awk '1' a
a
b
c
11. The print command of awk prints the line read, which is by default $0().
$ awk '{print;}' a
a
b
c
12. awk saves the line read from the file in the special variable $0. Hence, print $0 prints the line. In fact, in the earlier case, simply putting 'print' internally means 'print $0'.
$ awk '{print $0;}' a
a
b
c
13. perl solution. -e option is to enable command line option of perl. -n option is to loop over the contents of the file. -p options tells to print the every line read. And hence -pne simply prints every line read in perl.
$ perl -pne '' a
a
b
c
14. perl explicitly tries to print using the print command.
$ perl -ne 'print;' a
a
b
c
15. perl saves the line read in the $_ special variable. Hence, on trying to print $_, every line gets printed and hence the entire file. In fact, when we simply say 'print', it implies 'print $_'.
$ perl -ne 'print $_;' a
a
b
c
Happy file printing!!!

Note: If you know any other option to print the file content, please put it in the comments section.
Related Posts Plugin for WordPress, Blogger...

No comments:

Post a Comment