How do I remove newlines from a text file?

后端 未结 19 2311
遇见更好的自我
遇见更好的自我 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:03

    Assuming you only want to keep the digits and the semicolons, the following should do the trick assuming there are no major encoding issues, though it will also remove the very last "newline":

    $ tr -cd ";0-9"
    

    You can easily modify the above to include other characters, e.g. if you want to retain decimal points, commas, etc.

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

    To also remove the trailing newline at the end of the file

    python -c "s=open('filename','r').read();open('filename', 'w').write(s.replace('\n',''))"
    
    0 讨论(0)
  • 2020-11-29 18:05

    You can edit the file in vim:

    $ vim inputfile
    :%s/\n//g
    
    0 讨论(0)
  • 2020-11-29 18:06

    use

    head -n 1 filename | od -c 
    

    to figure WHAT is the offending character. then use

    tr -d '\n' <filename
    

    for LF

    tr -d '\r\n' <filename
    

    for CRLF

    0 讨论(0)
  • 2020-11-29 18:09
    paste -sd "" file.txt
    
    0 讨论(0)
  • 2020-11-29 18:11

    Using the gedit text editor (3.18.3)

    1. Click Search
    2. Click Find and Replace...
    3. Enter \n\s into Find field
    4. Leave Replace with blank (nothing)
    5. Check Regular expression box
    6. Click the Find button

    Note: this doesn't exactly address the OP's original, 7 year old problem but should help some noob linux users (like me) who find their way here from the SE's with similar "how do I get my text all on one line" questions.

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