I have an awk script in a bash script that I am starting to generalise.
I would like to put the string "$3" into a bash variable and use that variable in the awk script. This would allow me to easily update the script as needed.
For example:
NR > 1 && $3 != p {
#blah blah blah
printf("%s_%s%s", $3, header[i], OFS)
}
would become something like
foo="$3"
NR > 1 && $foo != p {
#blah blah blah
printf("%s_%s%s", $foo, header[i], OFS)
}
I've tried various combinations of foo="$3"
, ='$3'
, "$foo"
, '$foo'
, and ${foo}
and can't get it to work.
What am I doing wrong?
.
I want to replace each instance of "$3" with "$foo" so that I only need to update $foo if I want to change the script.
The complete awk script inside the bash script:
#!/bin/bash
#these are bash variables
file=$1
header=$(head -n1 $file)
############################
# awk script #
############################
read -d '' awkscript << 'EOF'
BEGIN { OFS = "\\t" }
/^@/ {
for (i = 1; i <= NF; ++i)
header[i] = $i
next
}
NR > 1 && $3 != p {
#output two blank lines if needed
if (print_blank) {
print "\\n"
}
print_blank = 1
for (i = 1; i <= 3; ++i)
printf("%s%s", header[i], OFS)
for (i = 4; i < NF; ++i)
printf("%s_%s%s", $3, header[i], OFS)
printf("%s_%s%s", $3, header[NF], ORS)
}
{ p=$3; print }
EOF
############################
# end awk script #
############################
#blah
#blah
#blah
awk "$awkscript" ${tmp} > ${output}
$3
coming from a positional parameter in your bash script?$3
coming from?