bashyq

How to replace forbidden characters in dynamic target filename of yq split


I want to split a k8s resource file with mikefarah/yq into individual files per resource. Obviously the target filename of the new files have to be dynamic.

A quite obvious naming-scheme for k8s resources is [kind-name]. So I came to this command.

 yq '.items[]' my-file.yaml -s '.kind + "-" + .metadata.name'

But the k8s name can contain characters like colons that are not allowed in a filename. If this happens, I get this error

Error: open ClusterRole-system:[...].yml: The filename, directory name, or volume label syntax is incorrect.

Is there a way to replace characters in the dynamic target filename?


Solution

  • You could use sub to replace any matching regex pattern with a given string. For example, to replace every colon or slash with an underscore, use sub("[:/]"; "_").

    yq '.items[]' my-file.yaml -s '.kind + "-" + .metadata.name | sub("[:/]"; "_")'