如何使用awk或grep从不同的行中选择数据?(How to use awk or grep to select data from different lines?)

编程入门 行业动态 更新时间:2024-10-28 18:27:52
如何使用awk或grep从不同的行中选择数据?(How to use awk or grep to select data from different lines?)

如果我在脚本中间,当前有这样的管道输入:

text sometext moretext text othertext more somemore futhertext text sometext moretext text othertext more somemore futhertext etc etc (the 2 patterns repeat)

我想选择第一行的2nd列和第二行的4th列,然后管道输出,所以我最终得到:

sometext furthertext

有没有办法做到这一点? 我知道awk '{print $2}'和awk '{print $4}'存在但是如何让它在不同的行上选择不同的列?

If I'm in the middle of a script which currently has piped input like this:

text sometext moretext text othertext more somemore futhertext text sometext moretext text othertext more somemore futhertext etc etc (the 2 patterns repeat)

and I want to select say the 2nd column for the first line and the 4th column for the second line and then pipe the output so I end up with:

sometext furthertext

Is there a way to do this? I know that awk '{print $2}' and awk '{print $4}' exists but how do I make it select different columns on different lines?

最满意答案

$ awk 'BEGIN{split("2 4",a)} NR in a {print $(a[NR])}' file sometext futhertext

或者如果你想重复每一行和第二行:

$ awk 'BEGIN{n=split("2 4",a)} {print $(a[(NR-1)%n+1])}' file sometext futhertext sometext futhertext etc

如果你想为第3行和第4行做不同的字段,它可以简单地扩展:

$ awk 'BEGIN{n=split("2 4 1 3",a)} {print $(a[(NR-1)%n+1])}' file sometext futhertext text somemore etc $ awk 'BEGIN{split("2 4",a)} NR in a {print $(a[NR])}' file sometext futhertext

or if you want it to repeat for EVERY 1st and 2nd line:

$ awk 'BEGIN{n=split("2 4",a)} {print $(a[(NR-1)%n+1])}' file sometext futhertext sometext futhertext etc

and if you want to do different fields for the 3rd and 4th lines too, it's trivially extensible:

$ awk 'BEGIN{n=split("2 4 1 3",a)} {print $(a[(NR-1)%n+1])}' file sometext futhertext text somemore etc

更多推荐

本文发布于:2023-08-03 10:45:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1388214.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   数据   awk   lines   grep

发布评论

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

>www.elefans.com

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