测试模式是否属于特定数据库

时间:2013-09-30 00:13:34

标签: shell unix scripting sed awk

我问了一个类似的问题,但答案似乎是给了我一些问题。我的总体目标是能够从特定数据库中删除某个记录。

databases.txt包含:

class grades

schema.txt包含:

grades name test1 test2 test3

class.db包含:

Nick 79 84 85
You 24 83 52
Her 84 98 55

所需的输入是:

./del.sh class test2 84

我的目标是删除test2和类所属的db中包含'84'的所有行。

我使用以下方法验证数据库是否存在:

awk '{ print $1 }' databases.txt >> temp.txt

if  grep -Fxq $1 temp.txt 
then
    rm temp.txt
    touch temp.txt
else 
    echo "Database name error. Exiting."
    rm temp.txt
    exit 1
fi

我当前的问题是验证test2属于属于用户输入的数据库的模式,如果该模式中不存在该字段,则打印错误消息。

我之前的回应是:

awk 'NR==FNR{a[$1]=$0;next}a[$2]~/$2/{print $0}' schemas.txt databases.txt

然而,它似乎没有真正检查正确,它打印不必要的数据库文件。我的删除记录的代码现在也是一种蠢事:

var=$(grep -c $3 $1.db)
delrec=$3

echo "There were" $var "records deleted from the $1 database."
sed -i "/$delrec/d" $1.db

1 个答案:

答案 0 :(得分:0)

#!/bin/ksh
SchemaRef="`sed -n \"/$1 / s/^[^ ]* //p\"`"
if [ -z ${SchemaRef}" ]
  then
    return 1
  fi

FieldNr="`sed -n \"/^${SchemaRef} / s/ /\
/gp\" schema.txt | grep -n | sed -n \"/:$2$/ s/^[^:]:/\1/p\"`"
if [ -z ${FieldNr}" ]
  then
    return 2
  fi

FieldBefore=$(( ${FieldNr} - 1 ))
sed -n "/\([^ ]\{1,\} \)\{${FieldBefore}\}$3 / !p" $1.db

类似的东西(这里没有unix验证)。如果在linux下使用(或使用GNU sed),请将-posix添加到sed参数