Skip to content

Instantly share code, notes, and snippets.

@janxkoci
Created January 27, 2022 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janxkoci/d62852474a007de4aeaf89bf71d41586 to your computer and use it in GitHub Desktop.
Save janxkoci/d62852474a007de4aeaf89bf71d41586 to your computer and use it in GitHub Desktop.
(g)awk script to rewrite a lgo file using legofit estimates, for use with legosim
#!/usr/bin/awk -f
## USAGE
## awk -f est2lgo.awk model_est.txt model.lgo
BEGIN {OFS="\t"}
# read EST file and save param values into array
# note: array includes also header, but that won't match, so nobody cares
NR==FNR {a[$1]=$2; next}
# read LGO file and apply param values
$2=="free" {
# rewrite name of current free param into $3
sub(/=[0-9].*/,"",$3) # POSIX
# take value for current param from the array and assign formatted value to $3
val=a[$3]
$3=$3"="val
}1 # print non-matching lines too
#!/usr/bin/gawk -f
## USAGE
## gawk -f est2lgo.gawk model_est.txt model.lgo
BEGIN {OFS="\t"}
# read EST file and save param values into array
# note: array includes also header, but that won't match, so nobody cares
NR==FNR {a[$1]=$2; next}
# read LGO file and apply param values
$2=="free" {
# save name of current free param into variable par
par=gensub(/=[0-9].*/,"",1,$3) # GAWK ONLY
# check the par against the array and assign formatted value to $3
if (par in a) $3=par"="a[par]
}1 # print non-matching lines too
@janxkoci
Copy link
Author

janxkoci commented Feb 13, 2022

Why two versions?

Well, I first wrote the gawk version, using the handy gensub() function, and when I was done, I realized it won't work with other versions of awk (like mawk or "bwk awk", which I think is the default on macOS). After a moment, I realized I could rewrite it a bit to make it POSIX compliant, so I did. But I still prefer the gawk version, so here are both and feel free to use whatever works for you 😎

Note that the POSIX version has a side effect - it deletes values for commented (unused) parameters. The gawk version keeps those intact.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment