awk print even fields of file

Hello:
I want to print out the even number of fields plus the first column as row identifiers.

input.txt
ID  X1 ID  X2 ID  X3 ID  X4
A  700 A 1200 A  400 A 1300
B 2000 B 1000 B 2000 B  600
C 1400 C  200 C 1000 C 1200
D 1300 D  500 D  600 D  200

and the output is:

output.txt
ID  X1   X2   X3   X4
A  700 1200  400 1300
B 2000 1000 2000  600
C 1400  200 1000 1200
D 1300  500  600  200

So far, I found the closest solution is:

awk '{ for (i=1;i<=NF;i+=2) $i="" } 1' input.txt > output.txt

Questions here:
1) How to print out the first column as wanted?
2) How does $i="" work at each loop?
3) I had thought the for-loop should start from 2 instead of 1 when the increment is 2. With initial field being 1, the output fields should be the odd columns if started from 1 as $1, $3, $5, $7, but the fact is the opposite. Why?
Thanks!

How about (quick and dirty):

awk '{ for (i=3;i<=NF;i+=2) $i="" } 1' input.txt
ID X1  X2  X3  X4
A 700  1200  400  1300
B 2000  1000  2000  600
C 1400  200  1000  1200
D 1300  500  600  200

$i = "" empties the respective field regardless of loop.
(i=1; sets the loop's start value, irrespective of the increment. The odd fields are emptied which is the desired action.

1 Like

Thanks!
I did not understand the script until I saw yours: The for-loop is to "exclude" the fields by "emptying" them with $i = "".
Correct me if I miss anything. Thank you again!

Yes, field i is emptied, for i=3...#fields.
At the end the remaining line is printed, 1 is short/geek for { print }

1 Like