0

My awk script search 2 patterns in the input log files and print the number from the second columns associated with the found patterns:

var=$(awk -F# '{for (i = 1; i <= NF; i++) {if (match($i, /^1\.[0-9]+\/\? GLU 166 N/)) {sub(/^1\./, "", $i); sub(/\/.*/, "", $i); if (first == "") first = $i; if ($i in b) {queue[++qn] = $i} a[$i]; next} else if (match($i, /^1\.[0-9]+\/\? CYS 44 O/)) {sub(/^1\./, "", $i); sub(/\/.*/, "", $i); if ($i in a) {queue[++qn] = $i} b[$i]; next} else if (match($i, /^1\.[0-9]+\/\? [A-Z]{3} [0-9]+ [A-Z][A-Z0-9]*/)) {sub(/^1\./, "", $i); sub(/\/.*/, "", $i); exclude[$i];}}} END {for (i = 1; i <= qn; i++) {j = queue[i]; if (! (j in exclude)) {print j; exit}} if (first == "") print "1"; else print first}' ${vizu}/hbonds/${output}_${lig_name}_hbondsALL_rep${i}.log)

Now I try to define the both searching patterns in the bash prior to the AWK main part and use it directly in AWK code:

search_pattern1='GLU 166 N'
search_pattern2='CYS 44 O'
var=$(awk -v pat1="${search_pattern1}" -v pat2="${search_pattern2}" -F# '{for (i = 1; i <= NF; i++) {if (match($i, /^1\.[0-9]+\/\? pat1/)) {sub(/^1\./, "", $i); sub(/\/.*/, "", $i); if (first == "") first = $i; if ($i in b) {queue[++qn] = $i} a[$i]; next} else if (match($i, /^1\.[0-9]+\/\? pat2/)) {sub(/^1\./, "", $i); sub(/\/.*/, "", $i); if ($i in a) {queue[++qn] = $i} b[$i]; next} else if (match($i, /^1\.[0-9]+\/\? [A-Z]{3} [0-9]+ [A-Z][A-Z0-9]*/)) {sub(/^1\./, "", $i); sub(/\/.*/, "", $i); exclude[$i];}}} END {for (i = 1; i <= qn; i++) {j = queue[i]; if (! (j in exclude)) {print j; exit}} if (first == "") print "1"; else print first}' input.log)

which gives me another output compared to the first version of the script (without external variables) indicating that it has been not correctly ..

James Starlight
  • 317
  • 1
  • 6
  • Please [include the error](https://meta.stackoverflow.com/questions/359146/why-should-i-post-complete-errors-why-isnt-the-message-itself-enough). Also, is there a difference when you write `-v pat1="${search_pattern1}" -v pat2="${search_pattern1}"` ? – Aserre Apr 05 '22 at 16:03
  • The [bash tag](https://stackoverflow.com/tags/bash/info) you added says `For shell scripts with syntax or other errors, please check them at https://shellcheck.net before posting here` so do that. – Ed Morton Apr 05 '22 at 16:17

1 Answers1

2

Check your scripts with shellcheck. Quote variable expansions - it's "$var", no $var. Add a space after -v to be poratble.

awk -v pat1="${search_pattern1}" -F'#' '{the..script}'
KamilCuk
  • 120,984
  • 8
  • 59
  • 111