Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

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?

like image 394
minerals Avatar asked Mar 28 '13 15:03

minerals


People also ask

How do I remove a string from an array in bash?

To really remove an exact item, you need to walk through the array, comparing the target to each element, and using unset to delete an exact match. Note that if you do this, and one or more elements is removed, the indices will no longer be a continuous sequence of integers.

How do I remove items from a list in bash?

One of the methods is “unset,” which is used to delete an element from a specific index and afterward replace it with some other array. Several other sets of elements can be deleted using: also. You can remove the list element from the end but only the solitary one using the pop() method.


1 Answers

This is one of many ways

set ${myarr[2]} echo $3 
like image 92
Zombo Avatar answered Oct 04 '22 20:10

Zombo