1

Basically, I'm trying to make a program that at one point needs to store coordinates. There is one part of the program where I need to separate one string into two so I an able to preform math on the two strings separately, then reattach the two strings. An example of how strings would need to be changed in a kind of pseudocode:

Var1="10 17"
separate Var1 into Var2 and Var3
#using the command echo "$Var1,Var2,Var3" here would output 10 17,10,17
#preform math on Var2 and/or Var3 here
Var1="$Var2 $Var3"

Part of the problem is that I can't just do

Var2=${Var1::-2}

or whatever the equivalent is for removing the first characters to remove the first or last two digits because these numbers could sometimes be more than 99 or less than 10. Note that I would like for the separator between the two numbers to be a space. Does anybody know how I could do this?

3

If the separator is a single space, use prefix and suffix stripping.

before_the_first_space="${Var1%% *}"
after_the_first_space="${Var1# *}"
before_the_last_space="${Var1%* }"
after_the_last_space="${Var1##* }"

Alternatively, take advantage of word splitting on unquoted variable substitutions. This treats each whitespace sequence as a separator and puts the result into an array. set -f disables wildcard expansion, set +f turns it back on.

set -f
parts=($Var1)
set +f
echo "${parts[0]}"

Alternatively, use the read builtin to split the variable into an array. read reads from standard input, so use a here string to pass the content of the variable as input.

read -r -a parts <<<"$Var1"

Both the unquoted-substitution method and the read method split based on the value of IFS.

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.