【问题标题】:Write data from 1st occurrence of string to last occurrence of a string in a file将数据从第一次出现的字符串写入文件中最后一次出现的字符串
【发布时间】:2016-08-26 02:33:34
【问题描述】:

我想使用 shell 脚本将字符串第一次出现和文件中最后一次出现之间的数据写入另一个文件。

我尝试使用以下 sed 命令打印字符串匹配所在的行。

sed -n '/Air/p' ashu.txt

示例:ashu.txt 包含

I am a good student
Air is polluted 
water is not free 
now Expensive Air will be

上面的 sed 命令给出如下输出

Air is polluted 
now Expensive Air will be

但我想要如下所示。

Air is polluted 
water is not free 
now Expensive Air

请容忍我在帖子中的文字对齐方式。

【问题讨论】:

  • 如果Air 只出现一次怎么办?
  • 然后它应该打印包含单词“Air”的那一行

标签: shell unix sed


【解决方案1】:

当我听说文件中的最后一个 某事时,我通常会想“把文件倒过来,然后……第一个 文件中的东西

所以:

sed -n '/Air/,$p' file | tac | sed -n '/Air/,$p' | tac

这是:

  1. 从第一个 Air 打印到文件末尾
  2. 反转该流
  3. 从第一个 Air 打印到流的末尾
  4. 反转该流以恢复原始顺序。

更多干燥:

f() { sed -n '/Air/,$p' | tac; }
f <file | f

【讨论】:

  • 我没有足够的勇气发帖,但你是对的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-05
  • 2022-01-13
  • 2011-04-19
  • 2011-04-19
  • 1970-01-01
  • 2012-03-17
  • 1970-01-01
相关资源
最近更新 更多