45

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?

1
  • The array elements are strings — copies of the lines. They are not themselves arrays of words or anything. You can split the array element up if you wish, but there's no automatic splitting of an array element into words. Mar 28, 2013 at 15:32

4 Answers 4

46

This is one of many ways

set ${myarr[2]}
echo $3
3
  • 2
    Recommend: set -- ${mayarr[2]} so that if the value in the array element is -x -e, your shell doesn't start tracing and exit on errors. Mar 28, 2013 at 15:54
  • 12
    a=( ${myarr[2]} ); echo ${a[3]} is equivalent, and doesn't overwrite the shell/function positional parameters which you may be using for something else.
    – chepner
    Mar 28, 2013 at 16:12
  • 1
    @chepner, I would suggest a=( "${myarr[2]}" ); instead.
    – Artfaith
    Dec 14, 2021 at 9:11
26

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
8

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

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.