8

I would like to format string using linux bash:

"<username>{0}</username><password>{1}</password>".format("user", "pass")

Output:

<username>user</username><password>pass</password>

What is the correct command to do this? I can use any other wildcard instead {0} and {1}

2
  • Is this line in a file or in a variable? Commented Oct 18, 2018 at 17:11
  • 1
    line in variable Commented Oct 18, 2018 at 17:12

3 Answers 3

13

From printf --help:

-v var    assign the output to shell variable VAR rather than display it on the standard output

So, what you need to do is just:

FMT='<username>%s</username><password>%s</password>'
printf -v VAR "$FMT" user pass
Sign up to request clarification or add additional context in comments.

1 Comment

You could highlight that user can also be a variable with printf "$FMT" $(whoami) 'passphrase'
8

Try this sort of parameter expansion:

TMPL="<username>\$U</username><password>\$P</password>"
REALNAME="Bobby"
REALPASS="Lamepass"

TMPL=${TMPL/\$U/${REALNAME}}
TMPL=${TMPL/\$P/${REALPASS}}
echo $TMPL

Comments

2

The syntax you are using seems to be python. Security aspects aside, you could directly call python:

var='"<username>{0}</username><password>{1}</password>".format("user", "pass")'
python3 -c "print($var)"

prints

<username>user</username><password>pass</password>

Comments

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.