0

I'm having trouble finding a way to print a specific column of a text file using the awk command.
I have the awk command within a FOR loop that is looping through a large number of directories and on each loop I utilize the awk command to print two columns from a text file containing a large number of columns. the first column I need stays the same through each looping process, so I'm able to use $1 without issue. The issue arises when I need to print a second column.
The second column I want printed by awk changes each iteration through the for loop. So far, What I have tried to do is this

#Simplified Example

count=1  # the counter starts at 1 because I will not be needing col 1

for i in $list; do

   count=count+1

   awk '{print $1 "\t" ${count}}' $file > ex_files.txt

done

Hopefully what I have written here makes sense. I've looked at may other help-pages to find what I'm doing wrong with my syntax but have been unsuccessful up to this point. Most examples where I have seen awk with a variable, it isn't a dynamic variable so I'm kind of stuck.
If there is a better command to do what I'm attempting to do as opposed to "awk", I'm open to that. please let me know if you need further clarification

Destrif
  • 2,104
  • 1
  • 14
  • 22
Jon
  • 21
  • 4

1 Answers1

0

I feel dumb because I spent a lot of time last night looking for the answer to the question and after 10 minutes of looking this morning I finally found the answer via this website

http://www.grymoire.com/Unix/Awk.html#uh-4

in the Dynamic Variable section, I saw that if I changed this about the syntax of the awk line

awk '{print $1 "\t" $'$count'}' $file > ex_files.txt

That it fixed the problem. This way, it pulls the Nth(+1) column from the $file after the Nth iteration.

Jon
  • 21
  • 4
  • Instead of embedding the variable directly, I'd recommend using `-v` to pass the variable: `awk -vc="${count}" '{ print $1 "\t" $count }'` – Mr. Llama Jul 07 '16 at 15:35
  • i tried using your suggestion, however it didn't quite work. once again, I don't purport to be a bash wiz by any means, but did you mean: `awk -v cnt="${count}" '{ print $1 "\t" $cnt }'` ? – Jon Jul 07 '16 at 15:45