6

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?

kuruvi
  • 641
  • 1
  • 11
  • 28
  • 1
    Possible duplicate of [Trying to split a string into two variables](http://stackoverflow.com/questions/20144593/trying-to-split-a-string-into-two-variables) – Cyrus Oct 24 '15 at 16:50

3 Answers3

10
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.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
3

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.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
0

I think a better solution would be to assign the result of splitting into an array. For example:

IFS='/' read -a array <<< "http://web.com/sub1/sub2/sub3/sub4/sub5/sub6"

Unfortunately, this will create 3 'extraneous' elements, which you will have to take care of!

echo ${array[*]}
http: web.com sub1 sub2 sub3 sub4 sub5 sub6

EDIT: In here ${array[1]} is an empty element!

Thejaswi
  • 26
  • 4