Printing every alternate columns in a text file

Hi,

I have a big matrix with 1 million columns and 21 rows, which is a tab delimited file. I would like to print every alternate columns into a new file. For each row, the start column will be always the first column.

For example the input file

1 2 4 5 8 0 7 9
2 5 6 3 0 6 9 2
3 6 3 6 6 0 2 1

the desired output

1 4 8 7
2 6 0 9
3 3 6 2

Please let me know how to do it in awk. I tried the following, but didn't work

awk -F'\t' '{ for (i=1;i<=NF;i+=2) print $i }' input.txt > output.txt

Please do a google site search before posting. It saves mutual times.

awk '{for(x=1;x<=NF;x++)if(x % 2)printf "%s", $x (x == NF || x == (NF-1)?"\n":" ")}'

You weren't too far off:

awk  '{for (i=1;i<=NF;i+=2) printf "%s ", $i; printf "\n" }' file
1 4 8 7 
2 6 0 9 
3 3 6 2 

If you want <TAB> separators, it gets a bit more tedious:

awk  '{DL=""; for (i=1;i<=NF;i+=2) {printf "%s%s", DL, $i; DL="\t"}; printf "\n" }' file
1    4    8    7
2    6    0    9
3    3    6    2
1 Like

Alternatively, with GNU sed:

sed -r 's/\t[^\t]*(\t|$)/\1/g' file

--
or in this case of course:

cut -f1,3,5,7 file

With 21 columns that would become:

cut -f1,3,5,7,9,11,13,15,17,19,21 file