hi,
Am trying to find a solution for finding a null column value inside a loop using array.
for eg:
two
three
five
From the above array myarray[0],myarray[3] and myarray[5] having null values. But when am trying to check that space using some condition its not working.
for (( i=0; i<"${#myarray[@]}"; i++ ))
do
space=""
if [[ "${myarray[$i]}" == "$space" ]]
then
echo "space is there"
else
echo "no space"
fi
done
#!/bin/sh
myarray0=( `cat abc` )
space=""
for (( i=0; i<"${#myarray[@]}"; i++ ))
do
space=""
if [[ "${myarray[$i]}" == "$space" ]]
then
echo "space is there"
else
echo "no space"
fi
done
This is my code and below is the file content current shell sh, and Linux OS
cat abc
You can't set myarray0 and use myarray in the rest of your code.
And, setting an array using myarray=( `cat filename` ) throws away all of your empty lines.
After that, it isn't clear whether multiple words on a line in your input file should be treated as a single element in your array or as one element for each word. Maybe the following will show you what you did wrong and give you a way to get what you seem to be trying to do:
#!/bin/bash
myarray0=( $(cat abc) )
myarray=( )
myarray2=( )
while read line
do myarray=( "${myarray[@]}" "$line" )
done < abc
unset line
while read -a line
do if [ ${#line[@]} -eq 0 ]
then myarray2=( "${myarray2[@]}" "" )
else myarray2=( "${myarray2[@]}" "${line[@]}" )
fi
done < abc
space=""
for (( i=0; i<${#myarray0[@]}; i++ ))
do if [[ "${myarray0[$i]}" == "$space" ]]
then echo "myarray0: empty line"
else echo "myarray0: data present on line: ${myarray0}"
fi
done
echo
for (( i=0; i<${#myarray[@]}; i++ ))
do if [[ "${myarray[$i]}" == "$space" ]]
then echo "myarray: empty line"
else echo "myarray: data present on line: ${myarray}"
fi
done
echo
for (( i=0; i<${#myarray2[@]}; i++ ))
do if [[ "${myarray2[$i]}" == "$space" ]]
then echo "myarray2: empty line"
else echo "myarray2: data present on line: ${myarray2}"
fi
done
Note that although this script specifies bash , it also works unchanged with recent version of ksh93 (and with older versions of ksh93 if you change read -a to read -A ).
With the input file abc containing:
one
three
five
six seven eight
it produces the output:
myarray0: data present on line: one
myarray0: data present on line: three
myarray0: data present on line: five
myarray0: data present on line: six
myarray0: data present on line: seven
myarray0: data present on line: eight
myarray: data present on line: one
myarray: empty line
myarray: data present on line: three
myarray: empty line
myarray: data present on line: five
myarray: data present on line: six seven eight
myarray2: data present on line: one
myarray2: empty line
myarray2: data present on line: three
myarray2: empty line
myarray2: data present on line: five
myarray2: data present on line: six
myarray2: data present on line: seven
myarray2: data present on line: eight