Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove ^M from a text file and replace it with the next line

Tags:

python

replace

So suppose I have a text file of the following contents:

Hello what is up. ^M
^M
What are you doing?

I want to remove the ^M and replace it with the line that follows. So my output would look like:

Hello what is up. What are you doing?

How do I do the above in Python? Or if there's any way to do this with unix commands then please let me know.

like image 309
user1452759 Avatar asked Aug 01 '12 08:08

user1452759


People also ask

How do I get rid of M in Vim?

How can I remove ^M characters from text files? A. ^M are nothing more than carriage return, so it is easy to use the search and replace function of vim to remove them. That will do the job.

How do you remove the next line in a text file?

Open TextPad and the file you want to edit. Click Search and then Replace. In the Replace window, in the Find what section, type ^\n (caret, backslash 'n') and leave the Replace with section blank, unless you want to replace a blank line with other text. Check the Regular Expression box.

How do you remove the N at the end of a string in Python?

Remove \n From the String in Python Using the str. strip() Method. In order to remove \n from the string using the str. strip() method, we need to pass \n and \t to the method, and it will return the copy of the original string after removing \n and \t from the string.


2 Answers

''.join(somestring.split(r'\r'))

or

somestring.replace(r'\r','')

This assumes you have carriage return characters in your string, and not the literal "^M". If it is the literal string "^M" then substiture r'\r' with "^M"

If you want the newlines gone then use r'\r\n'

This is very basic string manipulation in python and it is probably worth looking at some basic tutorials http://mihirknows.blogspot.com.au/2008/05/string-manipulation-in-python.html

And as the first commenter said its always helpful to give some indication of what you have tried so far, and what you don't understand about the problem, rather than asking for an straight answer.

like image 191
Tim Hoffman Avatar answered Sep 29 '22 13:09

Tim Hoffman


Try:

>>> mystring = mystring.replace("\r", "").replace("\n", "")

(where "mystring" contain your text)

like image 42
FLOZz Avatar answered Sep 29 '22 13:09

FLOZz