通过以T开头的每一行来编辑文本文件

2024-10-01 22:32:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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 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 '/TO/ a\
new line string' myfile.txt

Tags: toinfromtxt格式somecansed
3条回答

这将在第二次出现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.
sed 's|TO|\nTO|g'

最后一个参数“g”将全局替换为“TO”。因此,请确保消息不包含“TO”字符串。你知道吗

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

相关问题 更多 >

    热门问题