I have a text file with tab-separated columns which I'd like to process using awk.
Here's an example of such a file:
size=1\tname=foo\tweight=1.2
weight=2.5\tname=bar\tsize=2
What I want to achieve is to normalize the numeric value in columns whose content is like $field_name=<number>
to four decimal places and keep the rest as is. Here, $field_name
is a shell variable that is passed to awk and I'd like to use its value inside a regex.
Here's a snippet (which is not working of course). I'm particularly interested in fixing line #5 in the following awk script and not solutions using other tools, such as sed, perl, python, etc.
$ cat "${file}" \ # 1
| awk -F "\t" -v field_name="${external_var}" ' # 2
{ # 3
for (i = 1; i <= NF; i++) { # 4
if ($i ~ /$field_name=[0-9]*.?[0-9]+/) { # 5
split($i, kv, "=") # 6
$i = sprintf("%s=%.4f", kv[1], kv[2]) # 7
} # 8
} # 9
print $0 # 10
}'
$external_var
is a shell variable, butfield_name
is aawk
variable (and$field_name
, same as$ fieldname
or$ (fieldname)
would be the awk$
operator applied to the contents of thefield_name
variable to retrieve the corresponding field of the input record), so the title and description of your question is a bit confusing.