this is probably an easy/what-the-hell-is-that question: here a blueprint of the script where I load 4 variables $1 $2 $3 and $4 in a function 'myloop' say
file1
1 2 3
1 4 5
1 6 7
myloop () {
echo col=$1 $2 $3 $4
awk -v c1="$1" -v c2="$2" -F, 'BEGIN {
FS=" ";
}
{
xy =($c1*$c2);
}
END {
print "Product" $3 "and " $4 #this is where $3 (='h2') and $4 (='02') don't print
print "prod= " xy;
}' file1 > res.txt
}
myloop 2 3 h2 o2
expected output in res.txt
product h2 and 02
prod = 68
so as I said in the commented line in the code, I can't get to read $3 and $4.
I try passing $3 and $4 with
awk -v c1="$1" -v c2="$2" -vl1="$3" -v l2="$4" ...
and then call $l1 and $l2 in the print statement but that does not work.
any hint would be appreciated as I'm no expert (as you can tell) in scripting
Thanks in advance
CodePudding user response:
$ cat tst.sh
#!/usr/bin/env bash
myloop() {
echo "col=$*"
awk -v c1="$1" -v c2="$2" -v l1="$3" -v l2="$4" '
{
xy = $c1 * $c2
}
END {
print "Product", l1, "and", l2
print "prod =", xy 0
}
' file1
}
myloop 2 3 h2 o2
$ ./tst.sh
col=2 3 h2 o2
Product h2 and o2
prod = 68
l1
and l2
are bad choices for variable names though since l
looks far too much like 1
in many fonts and so obfuscates your code.
By the way, in your code in your question, this:
awk -F,
is changing FS from it's default value of a blank to a comma and then this:
BEGIN {
FS=" ";
}
is setting it back to the default blank value it had to begin with. Just don't do that.
CodePudding user response:
What you are looking for is called string interpolation and can be performed like so:
print "Product ${3} and ${4}"