Tuesday, August 30, 2011

5 different ways to join all lines in a file



  In one of our earlier articles, we saw how to fold a file using the fold command. In this article, we will see the different ways in which we can unfold the file, or in other words, different ways to join all the contents of the file in one single line.

Let us take a file with the following contents. The file contains user's name and user expertise. Every line in the file is of length 16. The below shown examples are different ways of how to unfold the file contents:
$ cat file
Badri Mainframes
Suresh Unix
Rajendar Clist
Sreedhar Filenet

1. The first method is using perl. Simply, remove the new line character(chomp) and print:
$ perl -ne 'chomp;print;' file
Badri Mainframes Suresh Unix      Rajendar Clist   Sreedhar Filenet
2. The second is using the tr command. Using the -d option, we simply remove the new line character:
$ tr -d '\n' < file
Badri Mainframes Suresh Unix      Rajendar Clist   Sreedhar Filenet
3. Finally, using awk, we use the printf command which prints without the new line character:
$ awk '{printf $0;}' file
Badri Mainframes Suresh Unix      Rajendar Clist   Sreedhar Filenet
4. The paste command comes really handly for requirements of this nature:
$ paste -s --delimiters="" file
Badri Mainframes Suresh Unix      Rajendar Clist   Sreedhar Filenet
    The option -s tells to join lines, and --delimiter option defines the delimiter. Since the requirement is simply to join the lines, the delimiter is left blank.

5. Finally, using the sed way:
$ sed -e :a  -e 'N;s/\n//;ta'  file
Badri Mainframes Suresh Unix      Rajendar Clist   Sreedhar Filenet
    This is little tricky. The N option tells to join the current line with the next line. And then we remove the new  line separator between the lines. And the same thing is repeated till the end. "ta" means loop to the label "a" which is defined in the beginning. In other words, repeat the same till the end of the file.


Happy Unfolding!!!
Related Posts Plugin for WordPress, Blogger...

1 comment:

  1. sometimes this is also referred to as converting columns to rows of a file.

    ReplyDelete