Verwenden einer Variablen in Anführungszeichen


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

In den obigen Codes möchte ich eine Variable für 0.050 0.050 0.050 definieren.Ich habe versucht, mit

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

, aber innerhalb der Anführungszeichen kann die Variable $value nicht definiert werden.Wie kann ich diese Variable in Anführungszeichen setzen?

4

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.

BEGIN {
  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" '
    BEGIN{
      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