使用 GREP 搜索文件的特定行

互联网 更新时间:2023-05-01 14:12:48

Tho*_*hor 6

使用sed替代(GNU SED):

解析.sed

1h                 # Save the first line to hold space
2,3 {              # On lines 2 and 3
  /my pattern/ {   # Match `my pattern`
    x              # If there is a match bring back the first line
    p              # and print it
    :a; n; ba      # Loop to the end of the file
  }
}

像这样运行它:

sed -snf parse.sed file1 file2 ...

或者作为单线:

sed -sn '1h; 2,3 { /my pattern/ { x; p; :a; n; ba; } }' file1 file2 ...

您可能还想发出文件名,例如使用您的示例数据:

解析2.sed

1h                 # Save the first line to hold space
2,3 {              # On lines 2 and 3
  /two/ {   # Match `my pattern`
    F              # Output the filename of the file currently being processed
    x              # If there is a match bring back the first line
    p              # and print it
    :a; n; ba      # Loop to the end of the file
  }
}

像这样运行它:

sed -snf parse2.sed file1 file2 | paste -d: - -

输出:

file1:file 1
file2:file 2

Sun*_*eep 6

$ awk 'FNR==2{if(/one/) print line; nextfile} FNR==1{line=$0}' 1.txt 2.txt
file 1

$ awk 'FNR==2{if(/two/) print line; nextfile} FNR==1{line=$0}' 1.txt 2.txt
file 2
FNR 将具有正在读取的当前文件的行号 使用FNR>=2 && FNR<=3,如果你需要一个行范围 FNR==1{line=$0} 将保存第一行的内容以备将来使用 nextfile 大多数实现都应该支持,但是如果您需要删除它,该解决方案仍然可以工作(虽然速度较慢)

更多推荐

文件,GREP

本文发布于:2023-05-01 14:12:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/hyzx/e8e48bf7b849e7a6bf36af7ad8d4f0fc.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   GREP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 98810文章数
  • 25695阅读数
  • 0评论数