【问题标题】:How to get the output from second value using sed如何使用 sed 从第二个值获取输出
【发布时间】:2013-07-15 06:39:17
【问题描述】:

我有一个包含以下内容的文件作为示例

cat test.log
hello
how are you?
terminating
1
2
3
terminating
1
2

当我使用 grep 命令在终止后显示输出时,如下所示。

sed -n '/terminating/,$p' test.log

terminating
1
2
3
terminating
1
2

我想要输出如下

terminating
1
2

谁能帮我解决这个问题?

【问题讨论】:

    标签: regex unix sed awk


    【解决方案1】:

    的代码:

    $ sed -n '/终止/{N;N;h};${g;p}' 文件 终止 1 2

    如果行匹配terminating,将它和接下来的两行存储在保持空间中。在$EOF 上打印三行。


    sedscript 示例:

    $ 猫脚本.sed /终止/{ ñ ñ H } ${ G p } $ sed -nf script.sed 文件 终止 1 2

    对于最后一个 terminating 之后的所有行:

    $猫文件 猫测试.log 你好 你好吗? 终止 1 2 3 终止 1 2 3 4 5 6 $ 猫脚本.sed H /终止/{ H } ${ G p } $ sed -nf script.sed 文件 终止 1 2 3 4 5 6

    【讨论】:

    • 如果使用上述命令,则会出现“sed : command garbled /terminating/{N;N;h};${g;p}”错误 :(
    • @user2582284 你可以尝试使用sed 脚本,请看我的例子。
    • 它正在工作:) ...但这仅适用于两行现在我有如下文本
    • 嗨 Captcha,它正在工作:) ...但这仅适用于两行,现在我有如下文本你好吗? terminating 1 2 3 terminating 1 5 6 7 8 9 10 但是您提供的命令未显示如下。 Terminating 1 5 6 7 8 9 10 It is given thotput as terminating 1 5 Please help on this.
    • 您好验证码,有没有其他方法可以不处理文件?我的意思是使用 sed 的单一语法,而不将选项放在文件中。
    【解决方案2】:

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

    sed -r '/^terminating/!d;:a;$!N;/.*\n(terminating)/s//\1/;$q;ba' file
    

    除非该行以terminating 开头,否则丢弃它。阅读更多行,丢弃以terminating 开头的行之前的任何行。在文件末尾打印出文件的其余部分。

    【讨论】:

      【解决方案3】:
      sed -n 'H;/terminating/x;${x;p}' test.log
      

      作为带注释的伪代码:

      for each line:
          append the line to the hold space     H
          if line matches /terminating/         /terminating/
             then set hold space to line        x
          on the last line:                     $
              get the hold space                x
              and print                         p
      

      注意:x 实际上交换了保持/模式空间。

      【讨论】:

      • 嗨,当我使用上述命令时,它通过输出为“无法识别的命令:H;/terminating/x;${x;p}'”。我尝试使用 X 的大小写并得到相同的输出
      • 你的平台是什么? sed 版本?
      猜你喜欢
      • 1970-01-01
      • 2013-04-14
      • 2021-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-11
      相关资源
      最近更新 更多