bash,如果然后脚本来解析文件 [英] bash, if then script to parse file

查看:49
本文介绍了bash,如果然后脚本来解析文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的要求是查看 F-5 配置.

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

类似于:

 If x=virtual
 grep for virtual | pool | destination

文件看起来像这样:

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
   }
}

推荐答案

plain bash,虽然可以很容易地转换为 POSIX sh.

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

其中 file 是您的数据.您可以将其更改为 "$1"并将文件作为脚本的参数.

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

<小时>

使用普通的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

给定的数据输出是:

 $ 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

这篇关于bash,如果然后脚本来解析文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆