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 c1. The first is the most common cat command:
$ cat a a b c
Another variant of "cat " will be:
cat < a2. 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 c3. 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 c4. 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 c5. Using the famous while loop of the shell:
$ while read line >do > echo $line >done < a a b c6. 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 c7. sed without any command inside the single quote just prints the file.
$ sed '' a a b c8. 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 c9. 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 c10. 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 c11. The print command of awk prints the line read, which is by default $0().
$ awk '{print;}' a a b c12. 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 c13. 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 c14. perl explicitly tries to print using the print command.
$ perl -ne 'print;' a a b c15. 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 cHappy file printing!!!
Note: If you know any other option to print the file content, please put it in the comments section.
No comments:
Post a Comment