Sharcoux
Sharcoux

Reputation: 6075

split a string delimited by a string in bash

I'm trying to split a string of this kind :

file1 -> file2

and expect to affect "file1" and "file2" to 2 variables.

I tried with IFS but it seems to work only for one character long (with IFS=" -> " I get "file1" and "> file2"...

Based on this article, I tried another approach :

awk 'BEGIN {FS=" -> "} {xxx}' <<< $f

The issue is that I don't succeed to affect $1 and $2 to a variable that I could use later...

Upvotes: 1

Views: 56

Answers (2)

Walter A
Walter A

Reputation: 19982

You can do this in several ways:

str="file1 -> file2"

echo "Fast"
var1="${str% -> *}"
var2="${str#* -> }"
printf "%s=%s.\n" var1 "${var1}" var2 "${var2}"

echo "With cut"
var1="$(echo ${str}|cut -d" " -f1)"
var2="$(echo ${str}|cut -d" " -f3)"
printf "%s=%s.\n" var1 "${var1}" var2 "${var2}"

echo "With read"
read -r var1 arrow var2 <<< ${str}

Upvotes: 1

Stefano d&#39;Antonio
Stefano d&#39;Antonio

Reputation: 6152

You can use $():

VARIABLE="$(awk 'BEGIN {FS=" -> "} {for(i=1;i<=NF;i++)print $i}' <<< $f)"

You can assign the results to an array:

ARRAY=( $(awk 'BEGIN {FS=" -> "} {for(i=1;i<=NF;i++)print $i}' <<< $f) )

And extract the values as separate variables:

${ARRAY[0]}
${ARRAY[1]}
and so on...

And assign it to your variables.

Upvotes: 1

Related Questions