0

i'm trying to read from a file "file", with a for loop before the awk, so the "$j" would refer to the j variable in the loop, now i'm trying to get the first field on that file using awk, so i tried using $$j, but it gets translated into process id because of the two dollar signs in row, how can i avoid this?

this is the code

for ((j = 1; j < $number_of_insertion_col; j++)); do
    var=$(awk -F"\t:\t" 'NR==1 {print "'$$j'" }' file)
done

sample input

"col1(pk)   :   col2    :   col3    :   "

my desired output is "col1(pk) in the firs iteration, then col2 in the second and so on and so forth

anubhava
  • 761,203
  • 64
  • 569
  • 643
brightstar2100
  • 117
  • 1
  • 8
  • 2
    Please add sample input (no descriptions, no images, no links) and your desired output for that sample input to your question (no comment – Cyrus Jan 04 '22 at 20:49
  • @Cyrus added those, thanks – brightstar2100 Jan 04 '22 at 20:52
  • 1
    This question is not about using shell variables. It's about NOT using shell variables. – Andy Lester Jan 04 '22 at 20:53
  • It's **extremely** unlikely that calling awk in a shell loop is the right approach for whatever it is you're trying to do. If you ask a new question about how to do whatever it is we can help you do whatever that is the right way (as opposed to helping you implement the wrong way). – Ed Morton Jan 05 '22 at 15:20

1 Answers1

1

You can pass the value to a variable using -v instead of directly injecting it to the code:

for (( j = 1; j < number_of_insertion_col; ++j )); do
    var=$(awk -F"\t:\t" -v j="$j" 'NR == 1 { print $j }' file)
done

This answers your question but you can provide more details so people can suggest how you might be able to accomplish your goal better.

konsolebox
  • 72,135
  • 12
  • 99
  • 105