【问题标题】:bash, if then script to parse file [closed]bash,如果然后脚本来解析文件[关闭]
【发布时间】:2012-10-05 19:46:48
【问题描述】:

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

类似:

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

【问题讨论】:

  • 您的某些格式似乎搞砸了。很难确切地弄清楚您要做什么。请您花点时间解决您的问题?
  • 另外,预期的输出是什么?
  • 你想要这个:if [[ "$x" == "virtual" ]]; then grep "virtual\|pool\|destination" file; fi ?
  • 我认为他的意思是如果x == section(在这种情况下为部分=虚拟)然后从该部分中获取池和目标(参数)。
  • 是的,我想搜索文件,当我看到 virtual 时它会返回:virtual vs_website、pool pl_website 和destination 11.11.11.11

标签: linux bash shell scripting


【解决方案1】:

普通的bash,虽然可以很容易地转换为 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" 并将文件作为脚本的参数。

用给定的数据测试,返回:

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

【讨论】:

  • 当我对完整文件运行它时,将
  • 好吧,根据您作为示例提供的数据格式,它应该可以工作。实际数据的格式是否与您的示例相同?示例中是否存在任何前导空格?
  • virtual vs_XXX_www_443 { snat automap destination xx.xx.xx.xx:https ip 协议 tcp 规则 short_redirect_xxx_secure 配置文件 { pr_http_ebiz_x_forwarded_for {} serverssl { serverside } tcp-lan-optimized {} wildcard.xxx.com {客户端 } } } 虚拟 vs_xxx_www_80 { snat 自动映射目标 xx.xx.xx.xx:http ip 协议 tcp 规则 short_redirect_xxx 坚持 pr_source_addr_avs 配置文件 { pr_http_ebiz_x_forwarded_for {} tcp-lan-optimized {}
  • @user1748054 不,这不起作用,cmets 不允许格式化。但是,您可以按照 ghoti 的建议编辑您的问题并在此处添加。您也可以尝试我在答案中添加的 awk 版本。
  • 给我发邮件,我可以给你发一份文件样本,看看你的想法。
猜你喜欢
  • 2021-02-01
  • 1970-01-01
  • 2020-02-09
  • 2013-08-30
  • 2011-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-25
相关资源
最近更新 更多