我有代码将模式附加到用户输入的文本文件中,如下所示;
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
假设用户输入,abcd ab12
然后命令附加在下面几行;
force abcd npos 0. .0001
force ab12 npos 0. .0001
我需要为单独的行的每个输入添加epos
和字符串,如下所示(对于与上面示例相同的输入);upos
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
如何修改pattern
选项以将这些行附加到数据文件中?
答案1
使用 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]
printf(3)
就像GNU 的一样libc
,在 GNU 中,指的是%<n>$s
awk
n格式后的第一个参数。
便携:
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
答案2
另一种允许动态指定“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