minerals
minerals

Reputation: 1335

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

Here is how I create my bash array:

while read line
do
   myarr[$index]=$line
   index=$(($index+1))
done < lines.txt

The file "lines.txt" constists of the following strings

hello big world!
how are you
where am I

After creation of ${myarr[@]} I can easily access every element (line) in this array issuing

echo ${myarr[2]}

But what if I want to extract just world!? Is it possible to extract world! from 0 element of the myarr? What's most important, is it possible to extract any last word from the myarr element?

I know that in python you can do myarr[0][3] and that will do the trick, how about bash?

Upvotes: 56

Views: 175130

Answers (4)

Amirouche
Amirouche

Reputation: 3776

to print specific element from array using the index :

echo ${my_array[2]}

to print all elements from array you do :

for i in "${my_array[@]}"
do
    echo $i
done

Upvotes: 13

Michael Pfaff
Michael Pfaff

Reputation: 1263

Similar to stephen-penny's answer, but without overwriting shell/function positional parameters.

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

Upvotes: 8

Gordon Davisson
Gordon Davisson

Reputation: 126108

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 @chepner's 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 it'll 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

Upvotes: 34

Zombo
Zombo

Reputation: 1

This is one of many ways

set ${myarr[2]}
echo $3

Upvotes: 51

Related Questions