如果参数存在,请查找特定字符串

时间:2016-09-06 01:38:26

标签: ksh

这是配置文件的摘录(让我们给它起一个名字" /var/mqm/mqs.ini"):

QueueManager:
    Name=MYEAIP2
    Prefix=/var/mqm
    Directory=MYEAIP2
    DataPath=/esb/wmq/data/MYEAIP2
QueueManager:
    Name=ASIAREPOSP1
    Prefix=/var/mqm
    Directory=ASIAREPOSP1
    DataPath=/esb/wmq/data/ASIAREPOSP1
QueueManager:
    Name=EAIGWP1
    Prefix=/var/mqm
    Directory=EAIGWP1
QueueManager:
    Name=MYEAIP3
    Prefix=/var/mqm
    Directory=MYEAIP3

我试图返回" DataPath"的值。 (如果存在)当我为" Name"提供特定值时。如果" DataPath"不存在,我返回一个默认值;

例如1:如果我提供" MYEAIP2"的输入值,则应返回" / esb / wmq / data / MYEAIP2"

例如2:如果我提供" EAIGWP1"的输入值,则应返回" / var / mqm / qmgrs" (默认值,因为没有相应的" DataPath")

我现有的代码将输入值提供为QMGR:

for QMGRs in `dspmq | cut -d ")" -f1 | cut -d "(" -f2`
do
    #<to insert code here with QMGRs as input, to be searched in "/var/mqm/mqs.ini">
done

2 个答案:

答案 0 :(得分:0)

我没有ksh。在这里,我展示了使用bash的快速/脏实现。它必须与ksh几乎兼容。

#!/usr/bin/bash

if [[ $# < 1 ]] ;then exit;fi
export myarg="$1";
export name=""; export prefex=""; export directory=""; export datapath="";

while read line
do
    # We have new block of QueueManager Information
    if [[ "$line" == "QueueManager:" ]]
    then
      # Look at what we gathered so far. If a match found, break the loop
      if [[ "$myarg" == "$name" ]] ;then break ;fi
      # No match found. Reset.
      export name=""; export prefix=""; export directory=""; export datapath="";
    else
        # Block continues. Gather info.
        tok="${line%%=*}"; val="${line##*=}"
        if [[ "$tok" == "Name" ]] ;then name="$val" ;fi
        if [[ "$tok" == "Prefix" ]] ;then prefix="$val" ;fi
        if [[ "$tok" == "Directory" ]] ;then directory="$val" ;fi
        if [[ "$tok" == "DataPath" ]] ;then datapath="$val" ;fi
    fi
done

echo "Name=<$name> Prefix=<$prefix> Directory=<$directory> DataPath=<$datapath>"

答案 1 :(得分:0)

如果您想拥有查找一个qmgr的代码并在循环中调用该代码,可以使用

for name in MISSING MYEAIP2 ASIAREPOSP1 EAIGWP1 MYEAIP3; do
   echo "Look for ${name}"
   awk -F "=" -v default=/my/default/path -v search="Name=${name}" \
      '/Queue/ {if (found) print dp; found=0; dp=default;}
       /DataPath=/ {dp=$2;}
       { if (index($0,search)!=0) found=1}
       END { if (found) print dp;} ' /var/mqm/mqs.ini
done

如果要搜索大量qmgrs,循环中的工作将重复多次。你可以用某种方式改变它(练习!),你有代码可以读/var/mqm/mqs.ini并输出像EAIGWP1=/my/default/path这样的行,并在grep中使用它:

grep -F <(dspmq | cut -d ")" -f1 | cut -d "(" -f2) <(yourNewAwkCommand) | cut -d= -f2