I have a tab delimited file with 2500 columns and 3000 rows. I would like to extract a specific column based on the header. By the way, this is being done in a while loop so each time a different column name will be selected.
Example file format:
a b c d e f g h
xy 1 2 f 21 4 5 6
qu 9 10 z 50 12 7 8
Desired output:
a b c d g
xy 1 2 f 5
qu 9 10 z 7
I was thinking to identify the column number, and then store the number as a variable and pass it under -f in cut. Example if we are selecting column "g" which here is the 7th field.
colNum=$(head -1 file.txt | tr '\t' '\n' | cat -n | grep "g" | cut -f 1)
cut -f1,2,3,4,"$colNum" file.txt > new_file.txt
I get the following error:
cut: fields and positions are numbered from 1
Try 'cut --help' for more information.
cat -n
right-justifies the line numbers, socolNum
contains whitespace before the7
. However I'd suggest using a tool like awk, datamash, or miller instead.