Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: How to split a string and assign multiple variables

Tags:

bash

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?

like image 579
kuruvi Avatar asked Oct 24 '15 16:10

kuruvi


2 Answers

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.

like image 136
Cyrus Avatar answered Oct 19 '22 14:10

Cyrus


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.

like image 33
Peter Cordes Avatar answered Oct 19 '22 14:10

Peter Cordes