kislyuk / yq

Command-line YAML, XML, TOML processor - jq wrapper for YAML/XML/TOML documents
https://kislyuk.github.io/yq/
Apache License 2.0
2.57k stars 82 forks source link

quote replaced yaml output? #118

Closed JonGilmore closed 3 years ago

JonGilmore commented 3 years ago

lets take the following simple yaml file named a.yml that I'd like to modify:

strategy: merge
hostname: corp.org.com
user: blah

I can replace the value in user easily like so: yq -y '.["user"] = "blah2"' a.yml

But, if I want to quote the replaced value of user, I cannot seem to find out a way to do this. For example, this yq -y '.["user"] = "\"blah2\""' a.yml yields:

strategy: merge
hostname: corp.org.com
user: '"blah2"'

Any thoughts on how I could achieve this? Obviously, this is an over-simplified version of what I'm actually trying to do, the string that ends up in user will have reserved characters that I believe I need quoted.

JonGilmore commented 3 years ago

hm, possibly related to https://github.com/kislyuk/yq/issues/34? still would like to confirm im not missing something obvious though

kislyuk commented 3 years ago

Any special characters in your replacement string will be quoted by the YAML serializer. You don't need to manually quote anything; in your example, what you have accomplished is quoting your string twice. If there's something else I'm missing, please feel free to provide an expanded example of what you're trying to do.

JonGilmore commented 3 years ago

hm, is , character that would need to be quoted in a yaml file? Some googling around show's it might be? I guess my original example might have been a little too simple. What I'm using yq for is to take a yaml list and convert it into a comma separated string. I'm doing this because the application configuration requires a giant string rather than a list (dumb, I know, but it's out of my control). Here's a closer example to what I'm doing. take this config file (a.yml):

repo-allowlist:
  - 'github.corp.com/repo1'
  - 'github.corp.com/repo2'

As I was saying, I need to convert this list into a string, I'm doing so with the following:

export repos=$(yq -r '."repo-allowlist" | @csv' a.yml | sed s/\",\"/,/g)

The above yields this:

echo $repos
"github.corp.com/repo1,github.corp.com/repo2"

Then, I take the repos and substitute it into the file itself:

yq -yi '."repo-allowlist"=env.repos' a.yml

Which then yields this:

cat a.yml
repo-allowlist: '"github.corp.com/repo1,github.corp.com/repo2"'

one option I've tried was to remove all quotes entirely by changing my sed to this: sed s/\"//g this would then change repos to:

echo $repos
github.corp.com/repo1,github.corp.com/repo2

and with that, my final result (after running yq -yi '."repo-allowlist"=env.repos' a.yml) is:

cat a.yml
repo-allowlist: github.corp.com/repo1,github.corp.com/repo2

Maybe I'm overthinking this entirely, and that string doesn't need to be quoted at all?