Find the answer to your Linux question:
Results 1 to 5 of 5
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    Chomp alternatives? Remove newline/carriage-returns

    Is there a command that I can use through the command prompt to remove all newlines from a file? I would like the text in a text file to be in one straight line.

    Is there a perl script that I could use that would accomplish the same thing? I don't know how to pass a file to chomp, so I would appreciate it if the code could be shown to me.

    Any other ways that you can think of? The KATE editor does not remove newlines, unfortunately.

    Thank you for reading!

  2. #2
    Here is a very simple 'standard input to standard output' version:

    while (<>) { chomp; print; }

    [name of perl program] <input_file >output_file
    This will, of course, place the first character of each line directly after the last character of the previous line. If you want the newline to be replaced with a space, you could do something like this:

     while (<>) { chomp; printf("%s ", $_); }
    This will, of course, add an [unnecessary] space at the end of the one-line output -- which, if you don't care, that is great -- but, if you do, then more code will be required...

  3. #3
    I greatly appreciate your help! I had found a bash command in these forums months ago to do the same thing, but I searched for an hour and couldn't find it again. I'm okay with using PERL, but for curiousity's sake would you know of the command that I have described?

  4. $spacer_open
  5. #4
    Linux Guru anomie's Avatar
    Join Date
    Mar 2005
    Here's an awk way to do it.

    [hector@troy ~]$ cat some-file 
    [hector@troy ~]$ awk '{ str1=str1 $0 }END{ print str1 }' some-file 
    [hector@troy ~]$ awk '{ str1=str1 $0 " "}END{ print str1 }' some-file 
    this should all be on one line
    First example is with no spaces, second example puts spaces between each concatenated line.

    But if you have carriage returns in the mix as well, that may be a different issue. (You might have to strip them out.)

  6. #5
    This will translate newlines into spaces:
    tr "\n" " " <input_file >output_file

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts