Select second field in text table with shell script I am writing a bash script to mount openshift service accounts into kubernetes objects. The right secret to use is highlighted in this text: 


$ oc describe sa sa-build-webhook-realworld
Name:                sa-build-webhook-realworld
Namespace:           your-eng2
Labels:              app=sa-build-webhook-realworld
Annotations:         &lt;none&gt;
Image pull secrets:  sa-build-webhook-realworld-dockercfg-4qz9g
Mountable secrets:   sa-build-webhook-realworld-token-bqtnw
                     sa-build-webhook-realworld-dockercfg-4qz9g
Tokens:              sa-build-webhook-realworld-token-bqtnw
                     sa-build-webhook-realworld-token-k7lq8
Events:              &lt;none&gt;


I want the code to be reasonably robust so I am thinking of this as a job for awk where I need "anything in column 2 that is a 'Mountable secret' that isn't the docker secret". Here is the logic I have come up with:

MOUNTABLE_SECRETS='Mountable secrets:'
SECRET_NAME=$(\
   oc describe sa sa-build-webhook-realworld \
   | sed $(printf 's/./&amp;,/%s' ${#MOUNTABLE_SECRETS}) \
   | awk  'BEGIN{FS=OFS=","} {if ($1 ~ /^[ \t]*$/) $1=ch; else ch=$1} 1'  \
   | grep "$MOUNTABLE_SECRETS" \
   | sed 's/[, ]*//g' \
   | awk -F':' '{print $2}' \
   | grep -v docker \
   | grep token)
echo "SECRET_NAME=$SECRET_NAME"


Basically, I insert a character just beyond the width of that phrase to cut the table in half, copy cells on the left into blanks below, then select the second column then grep what I am looking for. 

To my mind, it breaks things into pieces that can be understood. It works, but past experiences have taught me that someone looking to maintain that may not be best pleased. Since performance is not an issue what I am really aiming for is maintainability. I also want portability and I am looking to stick with to typical bash and coreutils tools. 

How might I improve that script?
Your idea to transform the table so that the implied keys explicitly appear on every row is an interesting one, but I think that it is overcomplicated.

The backslashes to indicate continuation lines are actually superfluous here, since an unfinished $( substitution automatically causes the command to be incomplete.  Similarly, ending a line with a | pipe would also cause the command to be continued, so that would be a better convention to follow than putting the | at the beginning of the following line.

In general, any combination of sed, awk, and grep would be better expressed using just an AWK script.  The AWK script below reads a key and value if there is a colon on a line, or just a value if there is no colon.

SECRET_NAME=$(
    oc describe sa sa-build-webhook-realworld |
    awk -F: '
        $2  { KEY=$1 ; VALUE=$2; sub("^ *", "", VALUE); }
        !$2 {          VALUE=$1; sub("^ *", "", VALUE); }
        KEY=="Mountable secrets" &amp;&amp; VALUE !~ /docker/ { print VALUE }
    '
)