Extracting wanted columns

Suppose

file1

1 
3
8
9

file2

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

I want to print columns listed in file 1 from file2. so the output will look like

1 3 8 9
1 1 0 1
1 1 0 0
0 0 1 1

Help me :slight_smile:

awk 'NR==FNR { C[++L]=$1; next } { printf("%s", $(C[1]) ); for(N=2; N<=L; N++) printf("\t%s", $(C[N]) ); printf("\n"); }' columns data
1 Like
$ awk 'BEGIN{while(getline< "file1"){a[i++]=$0;}}{for(j in a){printf("%s ",$a[j])}print ""}' file2
1 3 8 9 
1 1 0 1 
1 1 0 0 
0 0 1 1 

1 Like
cut -d' ' -f $(paste -sd, file1) file2

Regards,
Alister

3 Likes