1

I have a bash script wherein I need to check an array based on a condition and if it matches I need to print the lines after that particular match. My code is below:echo ${myArray[(($k+1))]} doesn't work .

i=0;
for j in `cat sdp_aDT_dhk1smc3_Periodic_20140711.log` 
do
    array[$i]=$j; 

    i=$(($i+1)); 

done 
k=0;

for k in myArray;
    do
          if   myArray[$k]="MEMORY" ;  then

             echo ${myArray[(($k+1))]}
          fi

 done
2
  • 1
    You are missing $ before (($k+1)). Commented Jul 16, 2014 at 9:44
  • Is that really your true code? at least myArray should be $myArray Commented Jul 16, 2014 at 9:48

3 Answers 3

1

If you just want to print the lines that match with your particular condition, please try

myArray=`cat sdp_aDT_dhk1smc3_Periodic_20140711.log`
for k in $myArray;
do
    if [ "$k" = "MEMORY" ]
    then
        echo "$k"
    fi
done
Sign up to request clarification or add additional context in comments.

Comments

0

You can read that file contents into an array plain and simple with:

array=($(cat fileName))

No loop necessary for that.

Now, to your original question: You seem to mix up array and myArray, or are they two different things? Let's assume they are meant to be the same; so then I think you want to output the items directly after the items MEMORY (that's what your code looks like). You can do that like this:

flag=false
for k in "${array[@]}"
do
    $flag && echo "$k"
    if [ "$k" = "MEMORY" ]
    then
        flag=true
    else
        flag=false
    fi
done

Comments

0

Simply:

#!/bin/bash
readarray -t myArray < sdp_aDT_dhk1smc3_Periodic_20140711.log
for i in "${!myArray[@]}"; do
    if [[ ${myArray[i]} == 'MEMORY' ]]; then
        printf '%s\n' "${myArray[@]:i + 1}"
        break
    fi
done
  • readarray converts lines from input to array
  • ${!myArray[@]} populates the indices, not the elements themselves
  • printf '%s\n' prints every argument as a single line (creates multiple lines).
  • "${myArray[@]:i + 1}" represents all elements after the matched element and expands to multiple arguments.

Refer to the Bash Reference Manual for everything.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.