Rish
Rish

Reputation: 826

using awk to print every second field

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.

Upvotes: 3

Views: 1204

Answers (1)

John1024
John1024

Reputation: 113814

$ 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 

Upvotes: 5

Related Questions