0

I'm reading a file like

state 100 NULL
operator 2 0 3 NULL

and I want to parse it to an array line wise to check it for certain conditions so what i actual do is:

#!/bin/bash
fileLines=$(cat file)
IFS=$'\n'
for line in $fileLines
do
    IFS=$' ' read -r -a lineArray <<< $line 
    echo ${lineArray[@]}
    if [[ ${lineArray["state"]} ]] ; 
    then
       echo "hit"
    fi
done

but it unfortunately comes back with the output

state 100 NULL
hit
operator 2 0 3 NULL
hit

even if I check for equality by using

if [[ ${lineArray[0]} == "state" ]] ;

it is still ignoring the condition I gave to the script. Is there a better way to check my array for conditions?

2
  • if [[ ${lineArray[0]} == "state" ]] ; works for me Commented Jun 20, 2013 at 12:26
  • @doubleDown your right. Seems that I made a mistake on this statement earlier. But the original code is not working. In fact, that i have to add some more conditions i prefer the code of fedorqui, it's very good readable. Commented Jun 20, 2013 at 12:29

2 Answers 2

1

Why don't you check it like this?

[[ "$line" == *"stat"*  ]] && echo yes

Test

$ t="operator 2 0 3 NULL"
$ [[ "$t" == *"stat"*  ]] && echo yes
$

$ t="stat 100 NULL"
$ [[ "$t" == *"stat"*  ]] && echo yes
yes
Sign up to request clarification or add additional context in comments.

4 Comments

To go along with this answer, you don't need to read the entire file into memory at once; just read it line-by-line: while read -r line; do ...; done < file.
So the -r makes it load just one line each time instead of the entire file?
read always just reads one line; the -r simply tells read not to process backslashes in the input specially.
Ah, right, so your proposal is to use while read instead of the for line in in the OP. Good one.
1

The array is indexed by integers, and it looks like any non-integer strings are coerced to zero, so ${lineArray["state"]} will always return ${lineArray[0]}. man bash is rather vague on the subject:

Referencing an array variable without a subscript is equivalent to referencing the array with a subscript of 0.

Based on the last line of code you posted, it's unclear what you actually are trying to accomplish with this code.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.