1

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

2 Answers 2

1

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}
Sign up to request clarification or add additional context in comments.

2 Comments

Where did you find the one with read ? I don't find the documentation and man read doesn't help a lot...
I learned this somewhere on SO, maybe at stackoverflow.com/a/19052249/3220113.
1

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.

1 Comment

I understand how I can print, but how can I use it later in the script ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.