簡體   English   中英

通過以TO開頭的每一行來編輯文本文件

[英]Edit a text file by starting each line with TO

我正在嘗試使用sed編輯文本文件。 該文本文件實際上是一條短信,已以.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.

上面的幾行表示.txt文件中其余各行的格式。 我希望這些行以TO開頭,並以該行的結尾結束(直到下一個TO)。

像這樣:

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.

我以為以下命令對我有用,但是找到TO后會創建新行。

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

這將在第二次出現TO時插入換行符

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

測試:

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.

使用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'

最后一個參數“ g”將全局替換“ TO”。 因此,請確保該消息不包含“ TO”字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM