I am trying to invoke awk inside a bash script and passing some bash variables values to it. Is there any way to get a count of these variables and print all which are passed to it inside awk.
No. of variables passed to awk would be dynamic.
Below example
#!/bin/bash
NAME="Dell"
SERIAL="12345"
echo "Hello" | awk -v a=$NAME -v b=$SERIAL '{ print a,b }'
Referenced, Working example, Irvur's answer in here
#!/bin/bash
function confirm_peers (){
header_def=("${header_def[@]:-None}")
read -r -p "Enter nodes from header[${header_def[*]}]: " -a header
header=("${header[@]:-${header_def[@]}}") ;
echo -e "\nInput Recorded - ${header[@]} \n"
}
createEncConfig()
{
/usr/bin/awk -f - <<-'EOE' ${header[*]} FS=":" $1
BEGIN {
count=1
for (i = 1; i < ARGC - 2; ++i) {
split(ARGV[i], ar, "=");
print ar[2]
}
print "\nCount=" ARGC -3
}
EOE
}
confirm_peers
# Making array content adaptable to awk input
for x in ${!header[@]} ; do header[x]="a=${header[x]}"; done
createEncConfig $1
Referenced - Easiest so far , Kusalananda's answer
#!/bin/bash
function confirm_peers (){
header_def=("${header_def[@]:-None}")
read -r -p "Enter nodes from header[${header_def[*]}]: " -a header
header=("${header[@]:-${header_def[@]}}") ;
echo -e "\nInput Recorded - ${header[@]} \n"
}
createEncConfig()
{
/usr/bin/awk -v args="${header[*]}" -f - <<-'EOE' FS=":" $1
BEGIN {
count=split(args,ar," ")
for ( x in ar ) {
print ar[x]
}
print "\n" count
}
EOE
}
confirm_peers
createEncConfig $1
Output : Just pass any dummy file
$ bash /tmp/a.bsh /tmp/enc1.txt
Enter nodes from header[None]: a b c d
Input Recorded - a b c d
a
b
c
d
Count=4
Thanks to all ..
echo ${#header[@]}
everywhere you want, to know how many arguments are there – αғsнιη Oct 13 '18 at 14:27awk
, soawk '{... ; print args; ....}' args=${#header[@]}
. or if you need valuesawk '{... ;split(args, intoArray [, separator]) ; print intoArray[1]; ....}' args="$(echo {header[@]})"
, better to useprintf
– αғsнιη Oct 13 '18 at 14:42awk
implementations shell variables are not available within BEGIN block and you will need convert thrm into awk variables with-v Var
, while I don't see any point of using it within BEGIN block. you also can do it byawk -F'SEP' '{ print NF }' <<<"${header[*]}"
in short that I moved into an answer – αғsнιη Oct 13 '18 at 16:04-v nargs=${#header[@]}
? – Jeff Schaller Oct 14 '18 at 00:41