awk -v input="$constrained" '
    BEGIN {
        n = split(toupper(input), user)
        fmt = "%-4s %-8s     NNN    0.050 0.050  0.050\n"
    /<< matched line >>/ {
        for (i=1; i<=n; i++)
            printf fmt, user[i], user[i]"_GPS"
' ./text_data > text_data_2

In the above codes, I want to define variable for 0.050 0.050 0.050. I tried using with

echo -n "##### numeric value?  ####?"
read value
fmt = "%-4s %-8s     NNN    $value $value  $value\n"

but within the quotation marks, $value variable cannot be defined. How can I define this variable inside the quotation marks?

1 Answer 1


You should be able to pass the variable using -v the same as you do for your input variable

awk -v input="$constrained" -v value="0.05"

then use sprintf within your BEGIN block to construct the format string e.g.

  n = split(toupper(input), user);
  fmt = sprintf("%%-4s %%-8s     NNN    %-4.3f %-4.3f %-4.3f\n", value, value, value, value);

Note the use of %% to produce literal % in the fmt string.

To test that it's constructing the correct format string, we can add print statements, first for the fmt string itself and then for the resulting print statement:

$ awk -v value="0.05" '
      fmt = sprintf("%%-4s %%-8s     NNN    %-4.3f %-4.3f %-4.3f\n", value, value, value, value);
      print fmt;
      printf(fmt, "test", "testval");
%-4s %-8s     NNN    0.050 0.050 0.050

test testval      NNN    0.050 0.050 0.050
  • awk -v input="$constrained" ' -v value="0.5" BEGIN { n = split(toupper(input)‌​, user) fmt = sprintf("\"%%-4s %%-8s NNN %-4f %-4f %-4f\\n\"", value, value, value); %it doesn't work. text_data file was created empty after executing the codes. Aug 17, 2016 at 15:02
  • @deepblue_86 I think I was overzealous with the escaping - please see revised version Aug 17, 2016 at 16:17

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.