I use the command

varioutput=$(awk '{print $j}' OFS=, data/damper.test_temp1.csv)

because I want to extract the j th value of a line of many values seperated by , . But when I want to use $varioutput it gives me always the whole line.

What am I doing wrong?

Actually I want to use

for ((j=1; j<=20; j++)); do
         varioutput=$(awk -F, -v jj="$j" '{print $jj}'  data/damper.test_temp1.csv)

So I am quite confused now weather I should use it like above or not? I get an error, but when I use it like

for ((j=1; j<=20; j++)); do
         varioutput=$(awk -F, '{print $j}'  data/damper.test_temp1.csv)

I still get the line.

Now the following was the solution

for ((j=1; j<=20; j++)); do
         varioutput=$(awk -F, -v k=$j '{print $k}'  data/damper.test_temp1.csv)
  • What error do you get? – Jesse_b May 9 at 14:27

You’re specifying the output field separator, not the input field separator; use this instead:

varioutput=$(awk -F, '{print $j}' data/damper.test_temp1.csv)

(or set FS instead of OFS).

I’m also assuming that j is a placeholder above, and that you’re replacing it statically with the appropriate value (for example, print $4).

To use another variable from script, you must pass it to awk

e.g. for RANK variable in shell

varioutput=$(awk -F, -v j=$RANK '{print $j}' data/damper.test_temp1.csv)

Generally speaking, if you start using AWK for small pieces of a script as in this example, it’s better to use AWK for more of the script.

  • @steeldriver I think j is a placeholder here, the real command would be print $3 or something like that. – Stephen Kitt May 9 at 13:56
  • ah yes that makes sense – steeldriver May 9 at 13:57
  • I add way to do it in case $j should be a real variable. – Archemar May 9 at 14:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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