I have to split a URL string and assign variables to few of the splits. Here is the string
http://web.com/sub1/sub2/sub3/sub4/sub5/sub6
I want to assign variables like below from bash
var1=sub2
var2=sub4
var3=sub5
How to do this in bash?
x="http://web.com/sub1/sub2/sub3/sub4/sub5/sub6"
IFS="/" read -r foo foo foo foo var1 foo var2 var3 foo <<< "$x"
echo "$var1 $var2 $var3"
Output:
sub2 sub4 sub5
Or with an array:
x="http://web.com/sub1/sub2/sub3/sub4/sub5/sub6"
IFS="/" read -r -a var <<< "$x"
echo "${var[4]}"
declare -p var
Output:
sub2 declare -a var='([0]="http:" [1]="" [2]="web.com" [3]="sub1" [4]="sub2" [5]="sub3" [6]="sub4" [7]="sub5" [8]="sub6")'
From man bash
:
IFS
: The Internal Field Separator that is used for word splitting after expansion and to split lines into words with the read builtin command.
This should work:
IFS=/ read -r proto host dummy var1 dummy var2 var3 dummy <<< "$url"
Or read -ra
to read into an array. read -r
makes backslash non-special.
This won't work in bash:
echo "$url" | read ...
because read
would run in a subshell, so the variables wouldn't be set in the parent shell.
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