2017-07-19 14 views
1

我有bash脚本(user_remove.sh)从文件名address_book中删除用户。 user_remove.sh执行以下操作:与用户交互的Bash脚本(如果发现多个匹配)

1)通过命令获得单个输入,例如参数,并将其分配给名称为变量的变量。 (name =“$ 1”)

2)grep从address_book的名称并重新指定输出wc命令并将结果存储在变量匹配中。

3)测试条件匹配大于1,如果是(零)回显消息将打印,“多个匹配;请选择一个删除”并与用户交互以确认(y/n)y删除匹配的用户。

#!/bin/bash 

name="$1" 

matches=$(grep "$name" address_book | wc -l) 


if [ "$matches" -gt 1 ] 
then 
    echo "More than one match; Please select one to remove" 
    echo "$name Remove (y/n)?" 
    read answer 

    if [ "$answer" = y ] 
    then 
      grep -v "$name" address_book > my_tmp/address_book 
      mv my_tmp/address_book address_book 

    elif [ "$answer" = n ] 
    then 
      exit 0 
    else 
      echo "I could not find $name in address_book" 

    fi 
fi 

address_book文件包含两个行数据:

test abc 
test xyz 

样品试验:

$./user_remove.sh test 
More than one match; Please select one to remove 
test Remove (y/n)?y 

这里是我的问题:我想输出是这样的:

More than one match; Please select one to remove 
test abc Remove (y/n)?y 
test xyz Remove (y/n)?n 

你能帮我解决这个问题吗?

谢谢

回答

1

这是对你有什么小调整。关键是在循环播放它们之前将匹配存储在数组中。

#!/bin/bash 

name="$1" 

# Find all matches 
matches=() 
while read -r match 
do 
    matches+=("$match") 
done < <(grep "$name" address_book) 

# Loop through matches if more than one found 
if [ "${#matches[@]}" -gt 1 ] 
then 
    for match in "${matches[@]}" 
    do 
     echo "More than one match; Please select one to remove" 
     echo "$match Remove (y/n)?" 
     read answer 

     if [ "$answer" = y ] 
     then 
      grep -v "$match" address_book > my_tmp/address_book 
      mv my_tmp/address_book address_book 

     elif [ "$answer" = n ] 
     then 
      exit 0 
     else 
      echo "I could not find $name in address_book" 
     fi 
    done 
fi 

但你可能真的想,这是什么...

#!/bin/bash 

name="$1" 

matches=() 
while read -r match 
do 
    matches+=("$match") 
done < <(grep "$name" address_book) 

if [ "${#matches[@]}" -gt 1 ] 
then 
    echo "More than one match; Please select one to remove" 
    for match in "${matches[@]}" 
    do 
     echo "$match Remove (y/n)?" 
     read answer 

     if [ "$answer" = y ] 
     then 
      grep -v "$match" address_book > address_book2 
      mv my_tmp/address_book address_book 
     fi 
    done 
elif [ "${#matches[@]}" -eq 1 ] 
then 
    echo "I found one occurence of $name in address_book" 
else 
    echo "I could not find $name in address_book" 
fi 
+0

喜感,感谢很多你的答案。你的想法对我来说工作得很好。在这里,我有一个问题这部分匹配+ =(“$匹配”)的含义是什么?你能告诉我吗? – user6420577

+1

Hi @ user6420577,很高兴它的工作。这将整个匹配(通过grep)行附加到名为matches的数组。它被引用来保留整条线而不是每一行的每一个字。 – flu

+0

也@ user6420577,如果你觉得这是正确的答案,你会好好检查它。谢谢! – flu