【问题标题】:Edit a text file by starting each line with TO通过以 TO 开头的每一行来编辑文本文件
【发布时间】:2013-06-28 22:50:40
【问题描述】:

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

【问题讨论】:

    标签: python unix sed awk


    【解决方案1】:
    sed 's|TO|\nTO|g'
    

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

    【讨论】:

      【解决方案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.
      

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-02-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-21
          • 2022-08-17
          • 2016-06-29
          相关资源
          最近更新 更多