0

How can I do a split on single quotes?

I was expecting some kind of escape but I've had no luck so far. Have a feeling this might not even be possible.

echo "{\"username\": \"hu'lk\"}" | jq -r '.username|split("\'")|join("")'

I expect to get {"username": "hulk"} but I don't. It wants me to close pipe dquote> instead.

I understand that there might be a better way to do it but the conditional replace is nested in a larger jq filter.

Froejo
  • 71
  • 9
  • 2
    The `'` from the `split` is interfering with the quotes from `jq -r ''`. Try changin to double quotes: `echo "{\"username\": \"hu'lk\"}" | jq -r ".username | split(\"'\") | join(\"\")"` – 0stone0 May 25 '21 at 14:29
  • 1
    @froejo -since this seems to be mainly a shell-related question, it might be a good idea to mention which shell you have in mind, e.g. by selecting a suitable tag. – peak May 25 '21 at 14:48
  • The comment by @0stone0 worked for me. I couldn't get it to escape correctly and converted to double quotes around the filter. Thanks! – Froejo May 25 '21 at 15:18

1 Answers1

1

You could use split("'") or

[splits("[']")]

Depending on which shell you use, the special characters in these may need to be escaped, so you might find it more convenient to use jq’s -f command-line option. If using bash, note that:

echo $'"\'"'

yields

"'"

For further insights, see e.g. How to escape single quotes within single quoted strings

gsub

Consider also gsub("'";"")

peak
  • 105,803
  • 17
  • 152
  • 177