Sedulous
Sedulous

Reputation: 53

How would I parse this string?

I have the string "http://example.com http://example2.com" how would I grep them into two different variables?

I'm very new to Linux. Thanks, all help is appreciated.

Upvotes: 1

Views: 51

Answers (4)

Dolda2000
Dolda2000

Reputation: 25855

As an altnerative answer to my previous one, you can also use the following syntax, which should be available in all standard shells:

EXAMPLE="http://example.com http://example2.com"
URL1="${EXAMPLE%% *}"
URL2="${EXAMPLE#* }"

You can see the Bash/Dash manpage for further information on how they work.

Upvotes: 2

C. K. Young
C. K. Young

Reputation: 223003

The other answers are all great, but there are many ways to skin this problem, so here's another. :-) Since your string is space-separated, and your shell's default separator (IFS) includes space, you can take advantage of this:

mystr="http://example.com http://example2.com"
set -- $mystr
foo=$1    # http://example.com
bar=$2    # http://example2.com

(The -- after set isn't strictly required in this instance, but it prevents some stupid things from happening in case your string happened to start with a dash for some reason.)

Upvotes: 2

Dolda2000
Dolda2000

Reputation: 25855

Spontaneously, I wouldn't use grep, but read:

EXAMPLE="http://example.com http://example2.com"
read URL1 URL2 <<<"$EXAMPLE"

The <<< syntax assumes that you're using Bash, however. Otherwise, you'd have to do it like this:

read URL1 URL2 <<EOF
$EXAMPLE
EOF

Upvotes: 2

user2110286
user2110286

Reputation:

Use for loop

str="http://example.com http://example2.com"
for word in $str
do
    echo $word
done

Upvotes: 2

Related Questions