How do I remove newlines from a text file?

后端 未结 19 2314
遇见更好的自我
遇见更好的自我 2020-11-29 17:34

I have the following data, and I need to put it all into one line.

I have this:

22791

;

14336

;

22821

;

34653

;

21491

;

25522

;

33238

;


        
相关标签:
19条回答
  • tr -d '\n' < file.txt
    

    Or

    awk '{ printf "%s", $0 }' file.txt
    

    Or

    sed ':a;N;$!ba;s/\n//g' file.txt
    

    This page here has a bunch of other methods to remove newlines.

    edited to remove feline abuse :)

    0 讨论(0)
  • 2020-11-29 18:21

    If the data is in file.txt, then:

    echo $(<file.txt) | tr -d ' '
    

    The '$(<file.txt)' reads the file and gives the contents as a series of words which 'echo' then echoes with a space between them. The 'tr' command then deletes any spaces:

    22791;14336;22821;34653;21491;25522;33238;
    
    0 讨论(0)
  • 2020-11-29 18:23
    tr -d '\n' < yourfile.txt
    

    Edit:

    If none of the commands posted here are working, then you have something other than a newline separating your fields. Possibly you have DOS/Windows line endings in the file (although I would expect the Perl solutions to work even in that case)?

    Try:

    tr -d "\n\r" < yourfile.txt
    

    If that doesn't work then you're going to have to inspect your file more closely (e.g. in a hex editor) to find out what characters are actually in there that you want to remove.

    0 讨论(0)
  • 2020-11-29 18:23

    You are missing the most obvious and fast answer especially when you need to do this in GUI in order to fix some weird word-wrap.

    • Open gedit

    • Then Ctrl + H, then put in the Find textbox \n and in Replace with an empty space then fill checkbox Regular expression and voila.

    0 讨论(0)
  • 2020-11-29 18:26

    Using man 1 ed:

    # cf. http://wiki.bash-hackers.org/doku.php?id=howto:edit-ed 
    ed -s file <<< $'1,$j\n,p'  # print to stdout 
    ed -s file <<< $'1,$j\nwq'  # in-place edit
    
    0 讨论(0)
  • 2020-11-29 18:26

    Use sed with POSIX classes

    This will remove all lines containing only whitespace (spaces & tabs)

    sed '/^[[:space:]]*$/d'

    Just take whatever you are working with and pipe it to that

    Example

    cat filename | sed '/^[[:space:]]*$/d'

    0 讨论(0)
提交回复
热议问题