bash, if then script to parse file [closed]

2019-09-21 09:09发布

问题:

My requirements is to look through a F-5 config.

Something like:

 If x=virtual
 grep for virtual | pool | destination

File looks like this:

virtual vs_website_443 {
snat automap
pool pl_website_443
destination 11.11.11.11:https
ip protocol tcp
persist pr_cookie_JSESSION_AP
profiles {
   oneconnect-ebiz-blah {}
  pr_http_ebiz_x_forwarded_for {}
   serverssl {
      serverside
  }
   tcp-lan-optimized {}
   wildcard.origin.website.com {
      clientside
   }
}

回答1:

plain bash, though can easily be converted to POSIX sh.

#!/usr/bin/env bash

in=0 # whether we are inside a 'virtual' block
     # such a block ends once we meet a line that starts with '}'

while read -r
do
    if [[ $REPLY =~ ^virtual ]]; then
        in=1
        echo "${REPLY% *}"
    elif (( in )); then
        if [[ $REPLY =~ ^pool ]]
        then echo "$REPLY"
        elif [[ $REPLY =~ ^destination ]]
        then echo "${REPLY%:*}" # or just "$REPLY" if you want the ':https' part
        elif [[ $REPLY =~ ^} ]]
        then in=0
        fi
    fi
done < file

where file is your data. You can change that to "$1" and give the file as an argument to the script.

tested with given data, returns:

virtual vs_website_443
pool pl_website_443
destination 11.11.11.11

using plain awk

awk '$1 == "virtual" { f=1; print $1,$2; next }         \
     f == 1 { if ($1 == "pool") { print }               \
              else if ($1 == "destination") { print }   \
              else if ($0 ~ /^}/) { f=0 }               \
     }' file

with the given data output is:

 $ awk '$1 == "virtual" { f=1; print $1,$2; next } f == 1 { if ($1 == "pool") { print } else if ($1 == "destination") { print } else if ($0 ~ /^}/) { f=0 } }' file
virtual vs_website_443
pool pl_website_443
destination 11.11.11.11:https