Issue in inserting null string in array

I am getting some values from a file and putting them in an array..but the null strings are not getting passed to the array. So during printing the elements ,the null string is not showing in the output. during array size calculation it is also excluding null.Please let me know how to do it.

[root]# cat testlog
              saveset name: ;
              saveset name: /;
              saveset name: /  ;
[root]#

 [root]# awk '/saveset name:/ {for(i=3;i<=NF;i++) {gsub("\"",""); printf( "%s ", $i )}; printf( "\n"); }' testlog |awk -F ";" '{print $1}'
 /
/
[root]# setnamearr=($(awk '/saveset name:/ {for(i=3;i<=NF;i++) {gsub("\"",""); printf( "%s ", $i )}; printf( "\n"); }' testlog |awk -F ";" '{print $1}'))
[root]# echo "${#setnamearr[@]}"
2
[root]# for ((i=0; i<"${#setnamearr[@]}"; i++)); do
> echo "${setnamearr}"
> done
/
/
[root]#
 

PLEASE DON'T modify posts if people have already answered, pulling the rug from under their feet!

On a vague specification without decent sample input and output data and detailed error description, you can expect very generic replies only:

  • How do you tell "null strings" from normal fields - two adjacent field separators?
  • What are the field separators - you seem to use awk 's default?
  • What is the purpose of the piped second awk command, why don't you do that in the first?
  • Why do you gsub the entire line in every field's loop?
  • Are you aware that the shell concatenates ALL whitespace into one space unless quoted? So, "null strings" might be lost here...
1 Like

As noted earlier, the arr=( ... ) construct discards leading and trailing space and the expansion of the variable also squeezes whitespace, and the empty fields are no longer recognised as fields during array assignment

Try this alternative instead (using your own awk approaches):

i=0
while IFS= read -r line
do
  setnamearr[i++]=$line
done< <(awk '/saveset name:/ {for(i=3;i<=NF;i++) {gsub("\"",""); printf( "%s ", $i )}; printf( "\n"); }' testlog | awk -F ";" '{print $1}') 

--
Note: The awk constructs will also squeeze spaces, so that would need some work as well

--
You could try this alternate approach using only bash shell:

i=0
while IFS=':;' read -r label val dummy
do
  if [[ $label == *"saveset name" ]]; then
    setnamearr[i++]=${val# }
  fi
done < testlog