How to execute (./myscript) inside awk or bash script?

妖精的绣舞 提交于 2020-12-26 11:04:20

问题


I would like to run a script within an awk command. I have a code ./myscript that calculates the likelihood between two entities; the results are listed in listfile.txt.

The input for ./myscript is a file with two columns generated randomly.

The purpose here is to know what input file (values) is the best for the calculation. If the condition (0.01<$8<0.5) is not verified, the code keep running until it gives the best (random input)

I did try this, but it doesn't keep executing the code

./rand_input_generator
./myscript

rms=` awk ' NR==1 {print $8}' listfile.txt`
echo $rms

awk 'BEGIN {
rrr=$rms;
min=0.01;
max=0.5;
    while(rrr > max) {
    while(rrr < min) {
    system("./rand_input_generator");
    system("./myscript.cmd");
}
}
} ' 

I seems like it doesn't go into a loop at all. any suggestions please?


回答1:


I think I see your dilemma. Try this:

function getvalue()
{
    local -a rms
    ./rand_input_generator
    ./myscript

    # No need for invoking gawk -- use bash array
    read -a rms < listfile.txt
    # Output eighth column/word
    echo ${rms[7]}
    # Echo to stderr/terminal
    echo ${rms[7]} 1>&2
}

rrr=$(getvalue)
min=0.01;
max=0.5;

# Let awk do the comparison, and print out "true" command or "false" command,
# evaluate the command, and loop based on return code
while $(awk -v rms="${rrr}" -v min="${min}" -v max="${max}" 'BEGIN {if (rms < min || rms > max) print "true"; else print "false"}'); do
    # Refresh the value
    rrr=$(getvalue)
done

In reality awk is really a string-processing language, not a math language, so I'd recommend this change to the last three lines if you have bc:

# Call bc to evaluate expression, returning 1 or 0 based on result, and check
while [[ $(echo "(${rrr} < ${min}) || (${rrr} > ${max})" | bc) -eq 1 ]]; do
    rrr=$(getvalue)
done



回答2:


Use awk's system() function:

Here an example

awk '{printf("%s ",$1); system("myscript " $2)}' file

the example is from this site https://unix.stackexchange.com/questions/72935/using-bash-shell-function-inside-awk




回答3:


Use awk's system function. The return value is the exit code.

!($8 >= 0 && $8 <= 0.05) { system("./myscript") }


来源:https://stackoverflow.com/questions/65221558/how-to-execute-myscript-inside-awk-or-bash-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!