How to extract a particular element from an array in BASH?

How to extract a particular element from an array in BASH?

This is one of many ways

set ${myarr[2]}
echo $3

You can extract words from a string (which is what the array elements are) using modifiers in the variable expansion: # (remove prefix), ## (remove prefix, greedy), % (remove suffix), and %% (remove suffix, greedy).

$ myarr=(hello big world! how are you where am I)
$ echo ${myarr[0]}      # Entire first element of the array
hello big world!
$ echo ${myarr[0]##* }  # To get the last word, remove prefix through the last space
world!
$ echo ${myarr[0]%% *}  # To get the first word, remove suffix starting with the first space
hello
$ tmp=${myarr[0]#* }    # The second word is harder; first remove through the first space...
$ echo ${tmp%% *}       # ...then get the first word of what remains
big
$ tmp=${myarr[0]#* * }  # The third word (which might not be the last)? remove through the second space...
$ echo ${tmp%% *}       # ...then the first word again
world!

As you can see, you can get fairly fancy here, but at some point @chepners suggestion of turning it into an array gets much easier. Also, the formulae I suggest for extracting the second etc word are a bit fragile: if you use my formula to extract the third word of a string that only has two words, the first trim will fail, and itll wind up printing the first(!) word instead of a blank. Also, if you have two spaces in a row, this will treat it as a zero-length word with a space on each side of it…

BTW, when building the array I consider it a bit cleaner to use +=(newelement) rather than keeping track of the array index explicitly:

myarr=()
while read line, do
    myarr+=($line)
done < lines.txt

How to extract a particular element from an array in BASH?

Similar to stephen-pennys answer, but without overwriting shell/function positional parameters.

a=(${myarr[2]})
echo ${a[3]}

Leave a Reply

Your email address will not be published. Required fields are marked *