1

I've two variables. One is the text with placeholders e.g. &a or &B. The other one contains the variables which should be inserted in the text. &a says it's the first word, &b says it's the second word. In the text they could be in random order. Delimiter is a whitespace. How could I do this in bash?

Example:

TEXT="Once &B a &a"
VAR="time upon"

# Result should be "Once upon a time"
0

2 Answers 2

5

Pure bash - without external commands:

VAR="time upon"
TEXT="Once &b a &a"
set -- $VAR
temp=${TEXT//&a/$1}
TEXT=${temp//&b/$2}
echo ==$TEXT==
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this works like a charm. Sorry that I missed to say that there could be up to 26 placeholders (a-z) AND sometimes there are not as much variables as placeholders. Eg. TEXT="Once &b a &c there &a peace &d &e &f"; VAR="was upon time"
-1

You need to use at least these 2 commands :

  • cut (to split your "VAR" variable)
  • sed (to replace your tokens)

2 Comments

This does not help - how should one use these command? Please add an example and explanation. Temporarily downvoted.
Now you have the good keywords (sed and cut), you can copy/paste them in google, can't you ? Before you had them, you couldn't, so I do think it helps. SO is not a place to do someone else homework.

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.