Note that there are some explanatory texts on larger screens.

plurals
  1. POPassing a Bash Array Element to an Awk Regex Expression
    text
    copied!<p>I've found several questions on how to pass variables from <code>bash</code> into <code>awk</code>, most notably the <code>-v</code> command, but I can't quite seem to get them to do what I want.</p> <p>Outside the script, the command I'm running is</p> <pre><code>awk '$2 ~ /^\/var$/ { print $1 }' /etc/fstab </code></pre> <p>Which searches <code>/etc/fstab</code> for JUST the <code>/var</code> partition, and should either print out the physical mount point, or if there isn't one, nothing at all.</p> <p>Now inside the script I have an array that contains numerous partitions, and what I want to do is iterate through that array to search fstab for each physical mount point. The problem comes in at the fact that the elements in the array have a <code>/</code> in them.</p> <p>So what I want to do (In horrifically incorrect awk) is:</p> <pre><code>PARTITIONS=(/usr /home /var tmp); for ((n=0; n&lt;${#PARTITION[@]}; n++)); do cat /etc/fstab | awk '$2 ~ /^\${PARTITIONS[$n]}$/ { print $1 }'; done </code></pre> <p>But I know that that's not correct. The closest I have right now is:</p> <pre><code>PARTITIONS=(/usr /home /var tmp); for ((n=0; n&lt;${#PARTITION[@]}; n++)); do cat /etc/fstab | awk -v partition="${PARTITIONS[$n]}" '$2 ~ /^\/var$/ { print $1," ",partition }'; done </code></pre> <p>Which at LEAST gets the partition variable into awk, but doesn't help me at all with matching it.</p> <p>So basically, I need to feed the array in, and get the physical partitions back out. Eventually the results will be assigned to another array, but once I get the output I can go from there.</p> <p>I also understand awk can remove the need for the cat at the beginning, but I don't know enough about awk to do that yet. :)</p> <p>Thanks for any help.</p> <p><strong>EDIT</strong></p> <pre><code>cat /etc/fstab | awk -v partition="${PARTITIONS[$n]}" '$2 ~ partition { print $1 }' </code></pre> <p>Approximates what I needed enough to be useful. I was focusing far too much on including the regex apparently. If anyone else could clean this up, it would be much appreciated :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload