组合多个 awk 函数

组合多个 awk 函数

我正在修改几个文件。我想将这三个 awk 函数组合成一个代码:

for i in *.gw; do
awk '/ALPHA_BF :/{sub(/^ *[0-9.]+/,"        #J     #")};{print}' $i > $i.tpl
done

for i in *.gw; do
awk '/REVAPMN:/{sub(/^ *[0-9.]+/,"        #G     #")};{print}'$i> $i.tpl
done

for i in *.gw; do
awk '/GW_REVAP :/{sub(/^ *[0-9.]+/,"        #I     #")};{print}' $i > $i.tpl
done

答案1

for file in ./*.gw; do
    awk '
        /ALPHA_BF :/{sub(/^ *[0-9.]+/,"        #J     #")}
        /REVAPMN:/  {sub(/^ *[0-9.]+/,"        #G     #")}
        /GW_REVAP :/{sub(/^ *[0-9.]+/,"        #I     #")}
        { print }' "$file" > "$file.tpl"
done

您可以为变电站部分定义单个函数:

for file in ./*.gw; do
    awk 'function do_sub(r) { sub(/^ *[0-9.]+/, "        #"r"     #") }
        /ALPHA_BF :/{ do_sub("J") }
        /REVAPMN:/  { do_sub("G") }
        /GW_REVAP :/{ do_sub("I") }1
    ' "$file" > "$file.tpl"
done

答案2

甚至 shell for 循环也可以放在 awk 中:

awk '
    FNR == 1     {close(outfile); outfile = FILENAME ".tpl"}
    /ALPHA_BF :/ {sub(/^ *[0-9.]+/,"        #J     #")}
    /REVAPMN:/   {sub(/^ *[0-9.]+/,"        #G     #")}
    /GW_REVAP :/ {sub(/^ *[0-9.]+/,"        #I     #")}
    {print > outfile}
' *.gw

答案3

您的意思可能是用管道符号链接 awk 命令。如果您需要组合不同的工具,可能会派上用场。如果所有工具都是 awk,则其他答案显示只需一次 awk 调用即可实现的良好解决方案。

for i in *.gw; do
    awk '/ALPHA_BF :/{sub(/^ *[0-9.]+/,"        #J     #")};{print}' $i |
    awk '/REVAPMN:/{sub(/^ *[0-9.]+/,"        #G     #")};{print}' |
    awk '/GW_REVAP :/{sub(/^ *[0-9.]+/,"        #I     #")};{print}' > $i.tpl
done

相关内容