Using the standard paste command, we can create a comma-delimited list of the field names in your second file (here called file2):
$ paste -s -d , - <file2 a1,a4
We can use this with Miller (mlr), a utility for processing structured documents (for example TSV files), and its cut subcommand to extract the first four fields along with the fields in file2 from the first file (here called file1):
$ mlr --tsv cut -f "chrom,pos,ref,alt,$(paste -s -d , - <file2)" file1 chrom pos ref alt a1 a4 10 12345 C T aa dd 10 12345 C T aa dd 10 12345 C T aa dd 10 12345 C T aa dd 10 12345 C T aa dd 10 12345 C T aa dd
The cut subcommand of Miller allows you to use the field names to select what fields to extract, and here we select the four first fields by name along with the names from the file2 file.
Since the cut subcommand also accepts a list of field names that end with a trailing comma, you could opt for using tr '\n' ',' <file2 in place of the paste command mentioned earlier.
If we had been given the field indices that we would want to retain, e.g. as the file file3 like this:
5 8
... then we could have used the standard cut command like below to extract the wanted data:
$ cut -f "1-4,$(paste -s -d , - <file3)" file1 chrom pos ref alt a1 a4 10 12345 C T aa dd 10 12345 C T aa dd 10 12345 C T aa dd 10 12345 C T aa dd 10 12345 C T aa dd 10 12345 C T aa dd
We can create the numerical field index list from the original files with a somewhat convoluted pipeline:
$ head -n 1 file1 | tr '\t' '\n' | grep -xF -f file2 -n | cut -d : -f 1 | paste -s -d , - 5,8
This extracts the header line from the data and replaces the tabs with newlines to get each field name on a separate line. The grep then outputs the line numbers from this that correspond to the field names in your second file. These are outputted on the form 5:a1, where the number before the : is the line number and the text at the end is the matching field name.
The number is isolated using cut, and the paste command is then used to get all the field indices into a comma-delimited list.
The full command, which emulates what the mlr command at the top of this answer does, would therefore look something like this:
cut -f "1-4,$( head -n 1 file1 | tr '\t' '\n' | grep -xF -f file2 -n | cut -d : -f 1 | paste -s -d , - )" file1
joindo this?joinutility uses numerical indexing of fields and compares the values of those fields from two files. In this case, the field indexes in the first file are unknown as the field names are given by the names in the second file. If the second file had contained only the field indexes (e.g., 5 and 8), then the ordinarycutcommand could have been used as incut -f "1-4,$(paste -s -d , - <file2)" file1bcftools?