在Linux下写脚本的时候, 通常需要根据某些字段对数据进行检索,也就是要实现一般数据库的select功能。在脚本里面这样的功能通常要求很简单, 数据结构也不太复杂, 不需要动用真正的数据库。基于txt格式的简单表是很好的选择,但仅仅使用bash并不太好实现查询, 一般需要通过perl,python来实现。 这里给了一个例子是使用awk来完成的,大家可以直接拿去使用。
两个文件:plaindb.awk是awk的代码, simple_select是bash的wrapper. 代码见后.
以下是定义的文本数据表的格式示例:
--- nodes.conf ------
#configure test nodes here
#format: nodename IP/hostname OStype root/Admin
#e.g.:   specjdriver 192.168.6.67 windows Administrator
#| nodename     hostname       ostype    admin |
specjdriver   192.168.6.67   windows   Administrator
specjsut      192.168.6.252  linux     root
specjdb       192.168.6.70   windows   Admin
specjemulator 192.168.6.66   linux     root
其中#开始的行是注释, 会被忽略. #|...| 行定义的是字段名字 其他行为数据.
下面是简单的使用例子:
[root@rac1 config]# ./simple_select nodes.conf nodename=specjdb hostname
192.168.6.70
[root@rac1 config]# ./simple_select nodes.conf ostype=windows nodename
specjdriver
specjdb
在脚本中用来做查询非常方便:)
附代码:
plaindb.awk:
------------------------------
#variable predefined:
# condition,columnids
BEGIN{
 # read condition
 count = split(condition,condstrs,"=");
 if(count != 2 )
  exit -1;
 keyid = condstrs[1];
 keyval = condstrs[2];
 # read schema
 do{
  res = getline;
 }while(res != 0 && $0 !~ /#\|.*\|/);
 if(res ==0 ){
#  print "no schema found!!"
  exit -1;
 }
 count = split($0,schema);
 colidcount = split(columnids,columnidarray,",")
 for(i=1;i<=colidcount;i++)
  columnindexarray[i] = -1;
 keyindex = -1;
# printf "searched: |%s|%s|\n",keyid,columnid;
 for(i=2;i<count;i++){
#  printf "|%s| - %d \n",schema[i], i;
  if(schema[i] == keyid)
   keyindex = i - 1;
  for(j=1;j<=colidcount;j++)
   if(schema[i] == columnidarray[j])
    columnindexarray[j] = i - 1;
 }
 if(keyindex == -1){
    #  print "no column found!", keyindex,columnindex;
  exit -1;
 }
 for(i=1;i<=colidcount;i++)
  if(columnindexarray[i]==-1)
   exit -1;
# print "Columns found!", keyindex,columnindex;
 do{
  res = getline row;
  if( res == 0){
#   print "reached the end";
   exit -1;
  }
  count = split(row,columns);
#  print count, ":", row;
  if(columns[keyindex] == keyval){
   for(i=1;i<=colidcount;i++)
    printf ("%s\t",columns[columnindexarray[i]]);
   printf("\n");
   continue;
  }
 }while(1);
  
}
/.*/{printf("");}
-----------------------------------------
simple_select:
-----------------------------------------
#!/bin/bash
CONDITION=$2
COL_ID=$3
awk -v condition="$CONDITION" -v columnids=$COL_ID -f ./plaindb.awk $1
----------------------------------------------------------------