当我匹配几个模式时,我想在分隔符之间检索文本

时间:2016-01-20 08:57:02

标签: sed

我有一个这样的文件:

define service {
        host_name       MyHOST
        service_description     Uptime
        obsess_over_service     1
        low_flap_threshold      0.000000
        high_flap_threshold     0.000000
        stalking_options        n
        freshness_threshold     5
        }
define service {
        host_name       MyHOST
        service_description     Users - Memory usage
        event_handler   notify-service-by-email
        obsess_over_service     1
        low_flap_threshold      0.000000
        high_flap_threshold     0.000000
        stalking_options        n
        freshness_threshold     5
        notes_url       rrd2graph.cgi?hostname=$HOSTNAME$&service=$SERVICEDESC$
        }
define service {
        host_name       MyHOST
        service_description     Users - Nr of Processes
        event_handler   notify-service-by-email
        obsess_over_service     1
        low_flap_threshold      0.000000
        high_flap_threshold     0.000000
        stalking_options        n
        freshness_threshold     5
        notes_url       rrd2graph.cgi?hostname=$HOSTNAME$&service=$SERVICEDESC$
        }
define service {
        host_name       MyHOST
        service_description     Users - Processor usage
        event_handler   notify-service-by-email
        obsess_over_service     1
        low_flap_threshold      0.000000
        high_flap_threshold     0.000000
        stalking_options        n
        freshness_threshold     5
        notes_url       rrd2graph.cgi?hostname=$HOSTNAME$&service=$SERVICEDESC$
        }

我希望在{和}之间检索文本,其中我匹配host_name和service_description。

我尝试了但它只返回host_name,service_description和fresh_threshold:

sed -n -e "/define service[[:space:]]*{/,/}/ {
                /host_name/ h
                /service_description/ H
                /freshness_threshold/G
                s/freshness_threshold.*$HOST.*service_description.*$SERVICE.*$/\0/p
        }" objects.cache

1 个答案:

答案 0 :(得分:0)

使用awk

awk -v RS="define service {|}" '/host_name *HOST/ && /service_description *SERVICE/' File

<强> Eample:

awk -v RS="define service {|}" '/host_name *MyHOST/ && /service_description *Users - Memory usage/' File

        host_name       MyHOST
        service_description     Users - Memory usage
        event_handler   notify-service-by-email
        obsess_over_service     1
        low_flap_threshold      0.000000
        high_flap_threshold     0.000000
        stalking_options        n
        freshness_threshold     5
        notes_url       rrd2graph.cgi?hostname=$HOSTNAME$&service=$SERVICEDESC$