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.
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, ; .
$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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With