2013-01-16 282 views
1
read -p "Please enter ID: " staffID 
id=$(grep -w "$staffID" record | cut -d ":" -f1 | sort -u); 
echo $id 

我试图从文件中grep正确的值有一些问题。grep精确整数匹配

以下内容存储在记录文件中。

12:Griffin:Peter:13:14:16 
14:Griffin:Meg:19:19:10 
10:Griffin:Loi:19:20:20 
130:Griffin:Stewie:19:19:19 
13:Wayne:Bruce:19:20:2 

我的第一列存储了始终唯一的id,这是我在grep中查找的内容。使用上面的代码,我只想找到由用户输入的唯一ID并显示在屏幕上,但是如果输入ID为13时显示13,那么我的回显会产生一个空值。任何想法可以解决这个问题?

回答

1
#!/bin/bash 
read -p "Please enter ID: " staffID 

#your code was commented out 
#id=$(grep -w "$staffID" record | cut -d ":" -f1 | sort -u); 

id=$(grep -oP "^${staffID}(?=:)" record) 
line=$(grep "^${staffID}:" record) 

echo $id #use this line if you just want ID 
echo $line #use this line if you want the line with given ID 

看到代码注释

注意 我不知道确切的要求,但我认为这样做的grep之前,检查用户输入的,如果他们输入有效的身份证件([0-9]+)可能?因为用户可能输入.*

+0

非常感谢,非常感谢! -oP在grep中寻找什么选项? – user1983064

+0

@ user1983064选项-o:仅显示匹配的零件。 -P使用perl正则表达式。 – Kent

+0

好的。我现在有与我的代码的另一个功能类似的问题,有没有一种方法,我可以通过确切的ID删除一行?我试过使用sed但无济于事:( – user1983064

0

似乎添加^到grep应该可以解决您的问题。

read -p "Please enter ID: " staffID 
    [[ "$staffID" =~ ^[0-9]+$ ]] || { echo "Enter only Numbers. Aborting" ; exit 2 ; } 
    id=$(grep -w "^$staffID" record | cut -d ":" -f1 | sort -u); 
    if [ "$id" == "" ]; then 
      echo "ID : Not found" 
    else 
      echo $id 
    fi 

我添加了一行来检查您的输入是否是有效的数字。