Convert string to an array in shell script [duplicate] - bash

This question already has answers here:
Bash: Split string into character array
(20 answers)
Closed 4 months ago.
How can ı convert a string to an array in shell script?
For example i want to put "apple" to an array.
array[0] = a
array[1]=p
array[2]=p
array[3]=l
array[4]=e
I tried a lot of things but none of them worked. I tried to use IFS but i have no space or comma in my word so it didn't work.

Parameter expansion is relevant here: ${#var} gives you the number of characters in var, and ${var:start:len} takes len characters from var, starting at position start.
Combine those two techniques and you get:
#!/usr/bin/env bash
string='apple'
array=( )
for ((i=0; i<${#string}; i++)); do
array[$i]=${string:i:1}
done
declare -p array
...which emits as output:
declare -a array=([0]="a" [1]="p" [2]="p" [3]="l" [4]="e")

Related

Bash initialize variable to a string that contains quotes and backslahes [duplicate]

This question already has answers here:
Setting an argument with bash [duplicate]
(2 answers)
Closed 5 months ago.
I have a string containing quotes and backslahes:
-options \'{"version": "http"}\'
I would like to initialize a variable PARAM with this string.
How this can be done in bash?
I thought of adding it to an array: PARAMS=(-options \'{"version": "http"}\')
but the output I am getting is: -options '{version: http}' i.e. without the slashes.
Expected output: -options \'{"version": "http"}\'
Can someone please suggest?
This looks ok to me.
test="-client-options \\'{\"quic-version\": \"h3\"}\\'"
echo "$test"
t2=("$test" "etc")
echo ${t2[#]}
Escape every inner " and double escape for a persisting escape

Bash variable name expansion in a loop [duplicate]

This question already has answers here:
Bash expand variable in a variable
(5 answers)
Closed 1 year ago.
I have several variables that have the name format of:
var0_name
var1_name
var2_name
And I want to be able to loop thru them in a manner like this:
for i in {0..2}
do
echo "My variable name = " ${var[i]_name}
done
I have tried several different ways to get this expansion to work but have had no luck so far.
Using the ${!prefix*} expansion in bash:
#!/bin/bash
var0_name=xyz
var1_name=asdf
var2_name=zx
for v in ${!var*}; do
echo "My variable name = $v"
# echo "Variable '$v' has the value of '${!v}'"
done
or equivalently, by replacing the for loop with:
printf 'My variable name = %s\n' ${!var*}
You may also consider reading the Shell Parameter Expansion for detailed information on all forms of parameter expansions in bash, including those that are used in the answer as well.

Split string into array in shell script based on regex delimiter [duplicate]

This question already has answers here:
Split a string only by spaces that are outside quotes
(4 answers)
Closed 2 years ago.
I have a string variable called JAVA_OPTS with various parameters in shell script.
-Dmaven.repo.local=/home/wangc/.m2/repository -Dtestparameter="some spaces" --add-exports=java.base/sun.nio.ch=ALL-UNNAMED
I'd like to split it into an array based on spaces, but not the space defined in escaped double quotes. For example I'd like to see an array with 3 elements:
-Dmaven.repo.local=/home/wangc/.m2/repository
-Dtestparameter="some spaces"
--add-exports=java.base/sun.nio.ch=ALL-UNNAMED
I have tried
IFS=' ' read -r -a array <<< "$JAVA_OPTS"
But it can't tell the different space between double quotes, and return a four elements array as:
-Dmaven.repo.local=/home/wangc/.m2/repository
-Dtestparameter="some
spaces"
--add-exports=java.base/sun.nio.ch=ALL-UNNAMED
Why do you require a regex solution? Getting the shell itself to parse this is significantly easier.
array=(-Dmaven.repo.local=/home/wangc/.m2/repository -Dtestparameter="some spaces" --add-exports=java.base/sun.nio.ch=ALL-UNNAMED)
Detouring the values via a string variable $JAVA_OPTS is precisely the wrong thing to do here, and makes the problem signicicantly harder.

Parse comma separated string of numbers into variables (scripting) bash [duplicate]

This question already has answers here:
How do I split a string on a delimiter in Bash?
(37 answers)
Closed 4 years ago.
The post marked as duplicate above is similar, however is not sufficient for the use case. The below answers show a minimalist use of the read command to put parsed input for a known length of delimiter separated values into helpfully-named variables. For instance, if I read all four vars into $STATEMENTS,$BRANCHES,$FUNCTIONS,$LINES - a loop is not ideal as it adds a minimal of loop index awareness or 4 more lines to put each array var into a helpfully named var.
I have a list of comma separated numbers in a file:
26.16,6.89,23.82,26.17
I'd like to read these 4 numbers into helpfully named separate variable names - there will never fewer or more than 4 numbers.
Thanks for any help!
You'll need read builtin. The input stream, and variables to read can vary, based on your personal preferences. For instance,
IFS=,
LIST=1,2,3,4
read a b c d <<<$LIST
echo $a ; echo $b ; echo $c ; echo $d

multiple substitutions on a string in bash [duplicate]

This question already has answers here:
Can ${var} parameter expansion expressions be nested in bash?
(15 answers)
Closed 7 years ago.
I have a variable named inet which contains the following string:
inet="inetnum: 10.19.153.120 - 10.19.153.127"
I would like to convert this string to notation below:
10.19.153.120 10.19.153.127
I could easily achieve this with sed 's/^inetnum: *//;s/^ -//', but I would prefer more compact/elegant solution and use bash. Nested parameter expansion does not work either:
$ echo ${${inet//inetnum: /}// - / }
bash: ${${inet//inetnum: /}// - / }: bad substitution
$
Any other suggestions? Or should I use sed this time?
You can only do one substitution at a time, so you need to do it in two steps:
newinet=${inet/inetnum: /}
echo ${newinet/ - / }
Use a regular expression in bash as well:
[[ $inet =~ ([0-9].*)\ -\ ([0-9].*)$ ]] && newinet=${BASH_REMATCH[#]:1:2}
The regular expression could probably be more robust, but should capture the two IP addresses in your example string. The two captures groups are found at index 1 and 2, respectively, of the array parameter BASH_REMATCH and assigned to the parameter newinet.

Resources