使用awk打印每个第二个字段 [英] using awk to print every second field

查看:455
本文介绍了使用awk打印每个第二个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  A = 1 = B = 2 = C = 3 

获得以下输出:

  1 2 3 

我试过了: p>

  awk'BEGIN {FS ==; OFS =} {for(i = 2; i <= NF; i + = 2); print($ i)}'input_file 

显然不起作用。我想我的for循环部分是正确的,但是我的打印部分出了问题。



谢谢

解决方案

  $ awk -v RS == -v ORS ='0 == NR%2'input_file 
1 2 3



工作原理



    $ b $设置输入记录分隔符为<$ c $, c> 。


  • -v ORS = p>

    将输出记录分隔符设置为空格。

  • %2



    每隔一行打印一次

    NR 是行号。 NR%2 是行号模2.因此,条件 0 == NR%2 在每个其他线路。当条件成立时,执行动作。由于没有指定任何操作,因此将执行打印记录的默认操作。

    原始代码中的关键问题是错误的分号。考虑:对于(i = 2; i <= NF; i + = 2)来说:

      print($ i)

    在这种情况下, print 命令仅在 循环退出之后执行。



    试试:

    $ $ $ awk'BEGIN {FS == ; print {$ i}'input_file
    1
    2
    3

    $ b $ p
    $ b $ p










    $ b $ $ awk'BEGIN {FS ==} {for(i = 2; i <= NF; i + = 2)printf%s,$ i; print}} input_file
    1 2 3


    I have the following input file and I wish to print every second field:

    A=1=B=2=C=3
    

    To get the following output:

    1 2 3 
    

    I have tried:

    awk 'BEGIN {FS="="; OFS=" "} {for (i=2; i<=NF; i+=2); print ($i) }' input_file
    

    and it clearly doesn't work. I think I have the for loop portion correct, but something is wrong with my print portion.

    Thank you.

    解决方案

    $ awk -v RS== -v ORS=" " '0==NR%2' input_file
    1 2 3
    

    How it works

    • -v RS==

      Set the input record separator to =.

    • -v ORS=" "

      Set the output record separator to a space.

    • 0==NR%2

      Print every other line.

      NR is the line number. NR%2 is the line number modulo 2. Thus, the condition 0==NR%2 is true on every other line. When the condition is true, the action is performed. Since no action is specified, the default action is performed which is to print the record.

    Alternative

    The key issue in the original code was a misplaced semicolon. Consider:

    for (i=2; i<=NF; i+=2); print ($i)
    

    In this case, the print command is executed only after the for loop exits.

    Try:

    $ awk 'BEGIN {FS="="; OFS=" "} {for (i=2; i<=NF; i+=2)print $i }' input_file
    1
    2
    3
    

    Or, if you want the output on one line:

    $ awk 'BEGIN {FS="="} {for (i=2; i<=NF; i+=2)printf "%s ", $i; print "" }' input_file
    1 2 3 
    

    这篇关于使用awk打印每个第二个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆