1

I am modifying several files. I want to combine these three awk functions into one single code:

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
0
4
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

you can define a single function for substations part:

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
0
3

Even the shell for loop can be put inside 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
-1

What you probably meant was chaining the awk commands with pipe symbols. Might come in handy if you need to combine different tools. If all tools are awk, the other answers show good solutions with only one awk call.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.