title: How to reorder lines of a file using a for loop and array using awk
body: <p>I have a situation in which I need to take an input file, reorder its lines by an order that is not determinable from the file but from an order that I can specify, then output the new order into a new file.</p>
  
  <p><strong>Input file</strong> (content changed for demonstration)</p>
  
  <pre><code>This should be line four
  This should be line six
  This should be line three
  This should be line two
  This should be line seven
  This should be line one
  This should be line five
  </code></pre>
  
  <p><strong>Expected output file</strong></p>
  
  <pre><code>This should be line one
  This should be line two
  ...
  This should be line seven
  </code></pre>
  
  <p>I thought awk may be the best approach, and that storing the desired order in an array then looping through it and pulling out the relative line might work.</p>
  
  <p>I have written the following to establish the array and loop through it, printing the line numbers in the order the output should be:</p>
  
  <pre><code>awk 'BEGIN { split("4 6 3 2 7 1 5",n); for(i=1; i&lt;=7; i++) print n[i] }'
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>4
  6
  3
  2
  7
  1
  5
  </code></pre>
  
  <p>Having used NR previously I thought I may be able to simply substitute <code>print n[i]</code> for <code>NR==n[i]</code> but this results in no errors but also a blank output.txt</p>
  
  <pre><code>awk 'BEGIN { split("4 6 3 2 7 1 5",n); for(i=1; i&lt;=7; i++) NR==n[i] }' file.txt &gt; output.txt
  </code></pre>
  
  <p>I'm looking for the most elegant solution to either successfully adapt my final attempt above to print the relative line numbers of file.txt into output.txt as per the array, or a better approach as a whole that I may not be aware of.</p>