如何使用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 furthertextIs 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 futhertextor 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 etcand 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更多推荐
发布评论