简体   繁体   中英

Edit a text file by starting each line with TO

I'm attempting to use sed to edit a text file. The text file is actually an sms text message that was sent to my email in a .txt format, but the formatting is not pretty. Thanks in advance for any assistance. For instance, a particular line:

TO YOUDate : 06/12/2013 09:52:55 AMHi can u pls pick up some bread from the store. TO :   Contact NameDate : 06/12/2013 10:00:10 AMI can in about 15 minutes. I'm still in a meeting.

The above lines represent how the rest of the lines in the .txt file is formatted. I would like the lines to start with TO and end with the completion of the line (until the next TO).

Like so:

TO YOUDate : 06/12/2013 09:52:55 AMHi can u pls pick up some bread from the store.
TO :   Contact NameDate : 06/12/2013 10:00:10 AMI can in about 15 minutes. I'm still in a meeting.

I thought the following command would work for me, but it creates a new line after it finds TO.

sed '/TO/ a\
new line string' myfile.txt

This will insert a newline at the second occurrence of TO

sed 's/TO/\nTO/2' myFile.txt

test:

temp_files > cat myFile.txt
TO YOUDate : 06/12/2013 09:52:55 AMHi can u pls pick up some bread from the store. TO :   Contact NameDate : 06/12/2013 10:00:10 AMI can in about 15 minutes. I'm still in a meeting.
temp_files >
temp_files > sed 's/TO/\nTO/2' myFile.txt
TO YOUDate : 06/12/2013 09:52:55 AMHi can u pls pick up some bread from the store.
TO :   Contact NameDate : 06/12/2013 10:00:10 AMI can in about 15 minutes. I'm still in a meeting.

Using python :

>>> import re
>>> spl = "TO"
>>> strs = "TO YOUDate : 06/12/2013 09:52:55 AMHi can u pls pick up some bread from the store. TO :   Contact NameDate : 06/12/2013 10:00:10 AMI can in about 15 minutes. I'm still in a meeting."
>>> lis = re.split(r'\bTO\b',strs)[1:]
for x in lis:
    print "{}{}".format(spl,x)
...     
TO YOUDate : 06/12/2013 09:52:55 AMHi can u pls pick up some bread from the store. 
TO :   Contact NameDate : 06/12/2013 10:00:10 AMI can in about 15 minutes. I'm still in a meeting.
sed 's|TO|\nTO|g'

The last parameter 'g' will replace "TO" globally. So make sure that the message does not contain "TO" string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM