0

I'm using Jenkins multi-line string parameter to append new entries to a yaml file. But then I want to format those entries to match the yaml syntax.

The desired end result is:

var:
  - subvar1
  - subvar2
  - subvar3
  ...

What I have done so far is:

I'm running a shell script which takes that multi-line string parameter (an environment variable) which looks like subvar1\nsubvar2\nsubvar3 and appends it into the yaml file. So, my line code looks like this:

printf "var:\n${HOSTNAMES}" >> ${WORKSPACE}/group_vars/all

The yaml file looks like this after that:

var:
subvar1
subvar2
subvar3

I am seeking assistance from you guys on how to add two spaces and a hyphen then a space before each line that comes after var:

EDIT: If SED or AWK is not a good idea to do this, what is a better way to do it?

9
  • 1
    Why not put the hostnames in an array, and then do { printf 'var:\n' ; printf ' - %s\n' "${HOSTNAMES[@]}"; } >> wherever? Commented Feb 28, 2017 at 18:02
  • @don_crissti, I'm pretty bad at sed/awk hence why I'm seeking help. Commented Feb 28, 2017 at 18:06
  • @steeldriver, I'll try that! Commented Feb 28, 2017 at 18:08
  • 1
    you need to iterate over ${HOSTNAMES[@]} with a for loop. for h in ${HOSTNAMES[@]}; do echo " - ${h}" >> file; done. Commented Feb 28, 2017 at 18:24
  • 1
    You could use a YAML parser for Perl or Python, or you could use something like this utility (written in Go). Commented Feb 28, 2017 at 18:55

2 Answers 2

1

If those are literal newlines in that variable, you can do:

HOSTNAMES='subvar1
subvar2
subvar3'
(IFS=$'\n'; printf -- "- %s\n" $HOSTNAMES)   # variable is unquoted
- subvar1
- subvar2
- subvar3

If you have the literal \ and n characters, then this has the same result:

HOSTNAMES='subvar1\nsubvar2\nsubvar3'
printf "$HOSTNAMES\n" | sed 's/^/- /'
1

With a bash array:

$ HostNames=( host1 "host two" host3 )
$ { printf 'var:\n' ; printf -- '  - %s\n' "${HostNames[@]}"; } > somefile
$ 
$ cat somefile
var:
  - host1
  - host two
  - host3

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.