I have a number of tab delimited files, for which the script user will be choosing one based on a particular threshold. All files have different amount of columns (1 to n depending on a previously chosen threshold). The columns of the files do not have headers, however for the next program, the chosen file will require headers. The columns need to be named Q1 to Qn for this next step. As the user will may be using a file with 1 or 10 or n columns, the number of columns to be names Q1 to Qn will change each time. I am having trouble getting this wo work properly. Any suggestions?

What I want to accomplish:


  • i.stack.imgur.com/dmJMt.png – user770211 Sep 11 '17 at 15:06
  • I am able to add the Q to the first row using: awk 'NR==1 {for (i=1;i<=NF;i++) {print "Q"$i;}}' file > outputFile , however how do I make the column number a header first? – user770211 Sep 11 '17 at 15:13

So, this is what I came up with. A bit messy and I think there is probably a faster way, but this worked.

for i in $(seq 1 $maxPops); do echo $i; done > output1.txt #make a temp file with numbers 1 to max populations maxPops
awk '{for (i=1;i<=NF;i++) {print "Q"$i;}}' output1.txt > outpu2.txt #Add Q to the beginning of each row name
cut -f1 output2.txt | paste -s > output3.txt #transpose the row names
awk -v OFS="\t" '$1=$1' inputPopFile.txt > chosenPop.txt #change single spaces to tab delimited spaces
cat output3.txt chosenPop.txt > renamedColumns.txt #add formatted column names to desired file chosenPop.txt
rm $fastStructure/temp1.txt $fastStructure/numPops.txt #remove unwanted files

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.