1

I have an array created and I want to look for a keyword and then if found, display the element that is n elements behind it. Is that possible to do with bash and if so, could someone provide an example? Example of operation:

element 1=red
element 2=blue
element 3=green

Parse through the array and if you see "green", display the element that is 2 behind it. In this case, it would return "red".

2 Answers 2

1
#!/usr/bin/env bash

val="blue"
array=("red" "green" "blue")

for (( i = 0; i < ${#array[@]}; i++ )); do
  if [[ $val == ${array[i]} ]] && (( i - 2 >= 0  )); then
   echo "${array[i - 2]}"
  fi
done

Outputs:

red

As @jordanm points out in the comments, you will need to worry about what might happen if an array index hasn't been set.

Sign up to request clarification or add additional context in comments.

2 Comments

Inside of an array's [] (I don't recall the proper term), is already numerical context. "${array[i + 2]}" will work. I upvoted because this is a good enough example to get the OP started, but there are other things to worry about such as arrays being sparse and what to do if i + 2 or i - 2 expands to null.
@jordanm: "subscript"? And I agree, it should be i - 2 based on the OP's use of the word "behind". Also, negative subscripts will cause an error in Bash versions before 4.2.
0
#!/bin/sh

val="blue"
offset=2 #offset index when echoing
array=("red" "green" "blue" "purple" "blue")

for i in $(seq $offset $[${#array[*]}-1])
do
    if [ "${array[$i]}" == "$val" ]
    then
    echo "${array[$[$i-$offset]]}"
    fi
done

All simple artihmetics can be done inside $[...]; don't forget the $ before the name of the variable. It is very useful when dealing with arrays in bash. note the offset at the beginning of the for-loop, avoiding useless tests of negative indexes.

2 Comments

Can you explain the offset? Does that mean +2 from the value needed? Can you also use negative numbers?
The offset is the number of elements between the current element and the display one (as in your example). For negative offset, it could work with a modification in the seq instruction: $(seq 0 $[${#array[*]}-1-$offset]). No modification is needed elsewhere. In order to make it working with positive and negative values, I suggest you to compute before the for loop the bounds of the seq instruction, depending on the sign of the offset, and start your for loop with for i in $(seq $begin $end)

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.