【问题标题】:Search for matching lines and combind the output on a single line搜索匹配的行并将输出合并到一行
【发布时间】:2012-03-23 23:53:24
【问题描述】:

我想在一个文本文件中搜索"\d+ [xyz]{3} \d+" 格式的三行,然后使用 sed 将这些行输出为一行。


示例输入:

... 
33 xxx 7
...
33 zzz 3
...
33 yyy 5
...

输出:

33 7 3 5

【问题讨论】:

    标签: sed awk


    【解决方案1】:

    使用awk:

    script.awk的内容:

    $1 ~ /^[[:digit:]]+$/ && $2 ~ /^[xyz]{3}$/ && $3 ~ /^[[:digit:]]+$/ {
        num = $1
        digits = digits " " $3
    }
    
    END {
        print num digits
    }
    

    infile的内容:

    text 
    33 xxx 7
    more text
    33 zzz 3
    55 n
    33 yyy 5
    66 asf sdf
    

    运行脚本:

    awk -f script.awk infile
    

    然后输出:

    33 7 3 5
    

    【讨论】:

      【解决方案2】:

      sed 的一种方式:

      script.sed的内容:

      ## Subbtitute line that matches the format with both numbers.
      s/^\([0-9]\+\) [xyz]\{3\} \([0-9]\+\)$/\1 \2/ 
      
      ## If substitution succeed, go to label 'a'.
      ta
      
      ## If substitution failed, go to label 'b'.
      bb
      
      ## Save content to 'hold space'.
      :a
      H
      
      ## In last line, get content from 'hold space', remove numbers
      ## not needed in output and print.
      :b
      $ {
          g   
          s/^\n//
          s/\n[0-9]\+//g
          p   
      }
      

      infile的内容:

      text 
      33 xxx 7
      more text
      33 zzz 3
      55 n
      33 yyy 5
      66 asf sdf
      

      运行脚本:

      sed -nf script.sed infile
      

      然后输出:

      33 7 3 5
      

      【讨论】:

        【解决方案3】:

        这可能对你有用:

        sed '/^\([0-9]\+ \)[xyz]\{3\} \([0-9]\+\)/{s//\1\2/;H};$!d;g;s/.//;s/\n[0-9]*//g' file
        33 7 3 5
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-03-21
          • 2011-04-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-08-20
          • 2018-03-25
          • 2013-10-30
          相关资源
          最近更新 更多