【问题标题】:How to read every line from a txt file and print starting from the line which starts with "Created_Date" in shell scripting [duplicate]如何从 txt 文件中读取每一行并从 shell 脚本中以“Created_Date”开头的行开始打印 [重复]
【发布时间】:2019-01-14 16:58:53
【问题描述】:
5G_Fixed_Wireless_Dashboard_TestScedule||||||||||||||||^M

Report Run Date||08/07/2018|||||||||||||||||||||^M

Requesting User Company||NEW|||||||||||||||||||||^M

Report Criteria|||||||||||||||||||||||^M

" Service Job Updated from Date:

  Service Job Updated to Date:

  Service Job Created from Date: 08/06/2018

   Service Job Created to Date:

 Service Job Status:

Resolution Code:"|||||||||||||||||||||||^M

Created Date|Job Status|Schedule Date|Job 
    Number|Service Job Type|Verizon Customer Order 
    Number|Verizon Location Code|Service|Installation 
    Duration|Part Number

我想从创建日期开始打印。结果 文件应该如下所示。

   Created Date|Job Status|Schedule Date|Job 
   Number|Service Job Type|Verizon Customer Order 
   Number|Verizon Location Code|Service|Installation 
   Duration|Part Number

在你们将我与其他一些问题联系起来后,我尝试了以下几行。但我的要求是将结果打印到同一个文件中。

FILELIST=find $MFROUTDIR -maxdepth 1 -name "XXXXXX_5G_Order_*.txt"

对于 $FILELIST 中的下一个文件;做

    cat $nextFile | sed -n -e '/Created Date/,$p'

完成

通过编写上面的代码行,输出将打印在控制台上。您能否建议一些方法将其打印在同一个文件中。

【问题讨论】:

  • 你有没有尝试过?这可以通过多种方式完成,例如bash、sed、awk 等
  • @NavyaNaiduChamidisetty:不在 cmets 中,请通过编辑您的问题添加此代码。
  • 首先,你真的不想写回同一个文件。但是,由于您将选择忽略该建议,因此您有很多选择。您可能会满足于简单地将 -i 添加到您的 sed 调用中。
  • @WilliamPursell 当我将 -i 添加到 sed 命令时,它表示“sed:没有输入文件”。我用过 cat $nextFile | sed -i -n -e '/创建日期/,$p'
  • @WilliamPursell 当我添加 cat $nextFile | 时它起作用了sed -i -n -e '/创建日期/,$p' $nextFile.感谢您的回复

标签: bash shell


【解决方案1】:

这可以通过一个简单的awk 命令轻松完成:

awk '/^Created Date/{p=1} p' file
Created Date|Job Status|Schedule Date|Job
    Number|Service Job Type|Verizon Customer Order
    Number|Verizon Location Code|Service|Installation
    Duration|Part Number

当遇到以Created Date 开头的行时,我们将标志p 设置为1。后面我们使用awk默认动作打印p==1时的每一行。


参考资料:

【讨论】:

  • 你能解释一下'{p=1}p'在上面的命令中做了什么吗?我对 shell 脚本完全陌生
  • 我没有使用 awk,我使用了 "cat $nextFile | sed -i -n -e '/Created Date/,$p' $nextFile" 并且成功了。
  • 我这里有一个小问题,例如当使用数据创建新文件时,它会在每行之后附加 ^M 字符。你能帮我解决这个问题吗?实际上,我在上面评论中提到的 cat 语句之后添加了这一行“sed -i -e 's/\^M//g' $nextFile”。但它没有用。我还在看^M
  • 由于您没有使用我建议的 awk` 解决方案,我无法提供建议。
猜你喜欢
  • 2011-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-18
  • 2017-12-26
相关资源
最近更新 更多