我正在 bash 脚本中构建模式pn_ere
、beg_ere
、 和end_ere
,最终在 awk 脚本中使用。我想在 awk 脚本内构造模式,用户能够为faml
和提供值asmb
,而不是传递完整的pn_ere
, beg_ere
, 和end_ere
。我该如何进行此更改?
nfaml=${faml:-"[[:graph:]]+"} # Use GPH if FAML null ("" or '')
nasmb=${asmb:-"[[:graph:]]+"} # Use GPH if ASMB null ("" or '')
kw=".*"
## Pattern pn_ere matches comment characters. ## ;; !! @c //
local pn_ere="^[[:space:]]*([#;!]+|@c|//)[[:space:]]+"
beg_ere="${pn_ere}(${nfaml}) ${ebl}(${nasmb})${ebr}${spc}(${kw})$"
end_ere="${pn_ere}END OF ${nfaml} ${ebl}${nasmb}${ebr}${spc}$"
awk -f "${trk}"/densel -v pn_ere="$pn_ere" \
-v beg_ere="$beg_ere" -v end_ere="$end_ere" \
"$filename"
答案1
这是你想要做的(未经测试)吗?
nfaml=${faml:-"[[:graph:]]+"} # Use GPH if FAML null ("" or '')
nasmb=${asmb:-"[[:graph:]]+"} # Use GPH if ASMB null ("" or '')
kw='.*'
awk -v nfaml="$nfaml" -v nasmb="$nasmb" -v kw="$kw" '
BEGIN {
ebl = "foo"
ebr = "bar"
spc = "whatever"
## Pattern pn_ere matches comment characters. ## ;; !! @c //
pn_ere = "^[[:space:]]*([#;!]+|@c|//)[[:space:]]+"
beg_ere = sprintf("%s(%s) %s(%s)%s%s(%s)$", pn_ere, nfaml, ebl, nasmb, ebr, spc, kw)
end_ere = sprintf("%sEND OF %s %s%s%s%s$", pn_ere, nfaml, ebl, nasmb, ebr, spc)
}
<... rest of script using the above ...>
' "$filename"
您也可以仅通过串联设置 beg_ere 和 end_ere,例如:
beg_ere = pn_ere "(" nfaml ") " ebl "(" nasmb ")" ebr spc "(" kw ")$"
sprintf()
但恕我直言,当字符串很长时,将格式与数据分开会更干净/更简单。