【问题标题】:Removing the following characters after a pattern in a text file in Unix在 Unix 中删除文本文件中的模式后的以下字符
【发布时间】:2014-01-06 14:40:15
【问题描述】:

我有一个文本文件,其中包含以下几行:

Customer Details Report - A03_2014-01-04_09-00-09.txt
DemandResetFailureReport_2014-01-04_11-00-08.txt
ExcessiveMissingReadsReport_2014-01-04_09-00-11.txt
LipaBillingSumCheckReport_2014-01-04_11-00-08.txt
LipaUsageBillingReport_2014-01-04_12-55-06.txt

我想在 UNIX 中运行一个命令(例如,sed),它将文本文件的内容编辑为:

Customer Details Report 
DemandResetFailureReport
ExcessiveMissingReadsReport
LipaBillingSumCheckReport
LipaUsageBillingReport

我遇到了一些命令,例如 sed '/^pattern/ d' 来删除模式后的所有行。但是命令中指定的文本文件在哪里呢?

【问题讨论】:

  • BTW sed '/^pattern/d' 删除所有开头带有单词 pattern 的行。如果您使用正则表达式而不是 ^pattern,它会删除与该模式匹配的所有行。

标签: regex shell unix sed awk


【解决方案1】:
grep -o '^[^-_]*' 

输出:

Customer Details Report 
DemandResetFailureReport
ExcessiveMissingReadsReport
LipaBillingSumCheckReport
LipaUsageBillingReport

【讨论】:

    【解决方案2】:

    使用awk,您可以将-_ 设置为字段分隔符(-F[-_])并打印第一个块({print $1}):

    $ awk -F"[-_]" '{print $1}' file
    Customer Details Report 
    DemandResetFailureReport
    ExcessiveMissingReadsReport
    LipaBillingSumCheckReport
    LipaUsageBillingReport
    

    【讨论】:

    • OP 不想在输出中包含 _2014
    • 已解决,刚刚离开awk 版本。谢谢,肯特 2014 :)
    • 最好确保引用 -F 模式。如果您有一个名为“_”的文件,或者您启用了 nullglob 选项,那么您就有麻烦了。
    【解决方案3】:

    我一直使用perl -pi,如下:

    $ perl -pi -e 's/[-_].*//' file
    $ cat file
    Customer Details Report 
    DemandResetFailureReport
    ExcessiveMissingReadsReport
    LipaBillingSumCheckReport
    LipaUsageBillingReport
    

    如果需要对原件进行备份,请为备份文件指定后缀,例如:

    $ perl -pi.bak -e 's/[-_].*//' file
    

    另请参阅以下有关就地编辑文件的主题:sed edit file in place

    【讨论】:

      【解决方案4】:

      我建议使用sed -i 's/[-_].*//' file.txt。您的文本文件(file.txt)必须作为参数(我选择了这种方式)或标准输入(sed 's/[-_].*//' < file.txt > file2.txt)传递,但这样您无法就地编辑它(-i)。确保不要将sed … <file.txt >file.txt 用作that will delete your file.txt contents

      【讨论】:

        【解决方案5】:

        这可能对你有用(GNU sed):

        sed -ri 's/( -|_).*//' file
        

        【讨论】:

          【解决方案6】:

          另一个awk

          awk '{sub(/[-_].*/,x)}1' file
          Customer Details Report
          DemandResetFailureReport
          ExcessiveMissingReadsReport
          LipaBillingSumCheckReport
          LipaUsageBillingReport
          

          这会删除您不想要的内容并打印其余部分。

          【讨论】:

            猜你喜欢
            • 2015-10-29
            • 2022-09-27
            • 2015-02-02
            • 2021-05-26
            • 2019-05-15
            • 1970-01-01
            • 1970-01-01
            • 2014-07-15
            • 2021-11-06
            相关资源
            最近更新 更多