Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a text string in bash to array

How do i convert a string like this in BASH to an array in bash!

I have a string str which contains "title1 title2 title3 title4 title5" (space seperated titles)

I want the str to modified to an array which will store each title in each index.

like image 963
Ayush Mishra Avatar asked Oct 29 '13 12:10

Ayush Mishra


People also ask

How do I convert a string to an array in Bash?

Using the tr Command to Split a String Into an Array in Bash It can be used to remove repeated characters, convert lowercase to uppercase, and replace characters. In the bash script below, the echo command pipes the string variable, $addrs , to the tr command, which splits the string variable on a delimiter, ; .

What does [- Z $1 mean in Bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What does %% mean in Bash?

The operator "%" will try to remove the shortest text matching the pattern, while "%%" tries to do it with the longest text matching. Follow this answer to receive notifications.


1 Answers

In order to convert the string to an array, say:

$ str="title1 title2 title3 title4 title5"
$ arr=( $str )

The shell would perform word splitting on spaces unless you quote the string.

In order to loop over the elements in the thus created array:

$ for i in "${arr[@]}"; do echo $i; done
title1
title2
title3
title4
title5
like image 86
devnull Avatar answered Sep 20 '22 21:09

devnull