3

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?

2 Answers 2

4

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
0

Another approach that allow to specify dynamicaly the list of "Xpos"

echo -n "WHICH STATIONS?"
read station

awk -v input="$station" -v 'xpos=npos epos upos' '
 BEGIN {
    n = split(tolower(input), user)
    m = split( xpos, Pos) 
    pattern=  "force %-4s %s 0. .0001\n"       
    }
  1
  /<< write after this line >>/ {
     for (i=1; i<=n; i++)
        for (j=1;j<=m;j++)
           printf pattern, user[i],Pos[j]
     exit
     }
' ./data > data_2

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.