Using printf function for repeated patterns

awkprintf

I have codes which append the patterns into text file w.r.t. the user's input as follows;

echo -n "WHICH STATIONS?"
read station
awk -v input="$station" '
 BEGIN {
        n = split(tolower(input), user)     
         pattern=  "force %-4s npos 0. .0001\n"       
    }
    {print}
    /<< write after this line >>/ {
        for (i=1; i<=n; i++)
             printf pattern, user[i]
        exit
    }
' ./data > data_2

let assume user's input abcd ab12 then commands append below lines;

force abcd npos 0. .0001
force ab12 npos 0. .0001

I need to add epos and upos strings for each input for separate lines as follows (for same inputs as above example);

force abcd npos 0. .0001
force abcd epos 0. .0001
force abcd upos 0. .0001
force ab12 npos 0. .0001
force ab12 epos 0. .0001
force ab12 upos 0. .0001

How can I modify the pattern option to append these lines into the data file?

Best Answer

With GNU awk:

pattern = "force %1$-4s npos 0. .0001\n" \
          "force %1$-4s epos 0. .0001\n" \
          "force %1$-4s upos 0. .0001\n"
[...]
printf pattern, user[i]

Like for the printf(3) of the GNU libc, %<n>$s in GNU awk, refers to the nth argument after the format.

Portably:

pattern = "force %-4s npos 0. .0001\n" \
          "force %-4s epos 0. .0001\n" \
          "force %-4s upos 0. .0001\n"
[...]
printf pattern, j=user[i], j, j
Related Question