<p>Below is my <code>testfile.yaml</code>:</p>
<pre><code>---
kind: Pod
metadata:
  name: amazing-application
---
kind: Deployment
metadata:
  name: amazing-deployment
---
kind: Service
metadata:
  name: amazing-deployment
---
kind: Service
metadata:
  name: tea-service
</code></pre>
<p>My goal is to split this into 4 files where the filename is <code>.metadata.name</code> and the dir that file goes into is <code>.kind</code>.</p>
<p>I have achieved what I want with this:</p>
<pre><code>for kind in $(yq e '.kind' testfile.yaml | awk '!/^(---)/' | uniq); 
do 
  mkdir &quot;$kind&quot;
  cd &quot;$kind&quot;
  yq 'select(.kind == &quot;'$kind'&quot;)' ../testfile.yaml | yq -s '.metadata.name' 
  cd ..;
done
</code></pre>
<p>What I want to know is how to get a unique together mapping, or somehow using multple criteria to split the testfile rather than through the loop.</p>
<p>Is there a way to use <code>yq</code> and <code>-s</code> or <code>select</code> to select where kind and metadata.name are unique together in that individual document (document as in separated by '---')?</p>
<p>Because if you do <code>yq -s '.kind' testfile.yaml</code> it will yield three yaml files, not four. Same for <code>yq -s '.metadata.name' testfile.yaml</code>; we get three files as not all <code>name</code> are unique - one gets lost.</p>

<p>There are a few ways you can do this direct in yq.</p>
<p>First of, you can use string concatenation with another property to comeup with a unique filename:</p>
<pre><code>yq -s '(.kind | downcase) + &quot;_&quot; + .metadata.name' testfile.yaml
</code></pre>
<p>That will create files like:</p>
<pre><code>deployment_amazing-deployment.yml
pod_amazing-application.yml
service_amazing-deployment.yml
service_tea-service.yml
</code></pre>
<p>Or you can use the built in $index to make the filenames unique:</p>
<pre><code>yq -s '.metadata.name + &quot;_&quot; + $index'
</code></pre>
<p>Which will create:</p>
<pre><code>amazing-application_0.yml
amazing-deployment_1.yml
amazing-deployment_2.yml
tea-service_3.yml
</code></pre>
<p>Disclaimer: I wrote yq</p>
