How do I remove newlines from a text file?

后端 未结 19 2312
遇见更好的自我
遇见更好的自我 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条回答
  • 2020-11-29 18:15
    $ perl -0777 -pe 's/\n+//g' input >output
    $ perl -0777 -pe 'tr/\n//d' input >output
    0 讨论(0)
  • 2020-11-29 18:16

    Was having the same case today, super easy in vim or nvim, you can use gJ to join lines. For your use case, just do

    99gJ
    

    this will join all your 99 lines. You can adjust the number 99 as need according to how many lines to join. If just join 1 line, then only gJ is good enough.

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

    Nerd fact: use ASCII instead.

    tr -d '\012' < filename.extension   
    

    (Edited cause i didn't see the friggin' answer that had same solution, only difference was that mine had ASCII)

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

    xargs consumes newlines as well (but adds a final trailing newline):

    xargs < file.txt | tr -d ' '
    
    0 讨论(0)
  • 2020-11-29 18:19

    I would do it with awk, e.g.

    awk '/[0-9]+/ { a = a $0 ";" } END { print a }' file.txt
    

    (a disadvantage is that a is "accumulated" in memory).

    EDIT

    Forgot about printf! So also

    awk '/[0-9]+/ { printf "%s;", $0 }' file.txt
    

    or likely better, what it was already given in the other ans using awk.

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

    I usually get this usecase when I'm copying a code snippet from a file and I want to paste it into a console without adding unnecessary new lines, I ended up doing a bash alias
    ( i called it oneline if you are curious )

    xsel -b -o | tr -d '\n' | tr -s ' ' | xsel -b -i
    
    • xsel -b -o reads my clipboard

    • tr -d '\n' removes new lines

    • tr -s ' ' removes recurring spaces

    • xsel -b -i pushes this back to my clipboard

    after that I would paste the new contents of the clipboard into oneline in a console or whatever.

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