0

我正在尝试使用 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
4

3 回答 3

2

这将在 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.
于 2013-07-01T18:14:13.687 回答
2

使用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.
于 2013-07-01T18:14:47.760 回答
1
sed 's|TO|\nTO|g'

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

于 2013-07-01T19:01:48.807 回答