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?

  • 1
    Why not put the hostnames in an array, and then do { printf 'var:\n' ; printf ' - %s\n' "${HOSTNAMES[@]}"; } >> wherever? – steeldriver Feb 28 '17 at 18:02
  • @don_crissti, I'm pretty bad at sed/awk hence why I'm seeking help. – Fadi Feb 28 '17 at 18:06
  • @steeldriver, I'll try that! – Fadi Feb 28 '17 at 18:08
  • 1
    you need to iterate over ${HOSTNAMES[@]} with a for loop. for h in ${HOSTNAMES[@]}; do echo " - ${h}" >> file; done. – DopeGhoti Feb 28 '17 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). – Satō Katsura Feb 28 '17 at 18:55
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.