什么是Vi命令从用户输入中删除文件中的行?

时间:2011-05-15 20:09:05

标签: bash shell unix line

我有一个文件,想要在用户在UNIX / Vi中输入ID时删除行。

该文件名为“users”,包含:

001:joe:one:20:01:02 
002:joe:two:21:06:02
003:joe:three:22:05:02
004:joe:four:23:04:02

我在Vi中使用了以下功能:

 function deleteRecord()
  {

    echo "Please enter staff ID: "
    read userID

#store staffID in variable
    sID=$( grep -w "$userID" users )

    #store staff details only if user does not exist
    #else prompt them to input again until they enter unused data
    if [ $? -ne 0 ]
    then
            echo "Sorry that user does not exist!"
            echo "Try entering a different staff ID to delete"
            deleteRecord
    elif [ $? -eq 0 ]
    then
                    #:g/^$userID:/d

                    #sed /$userID/d users >tmp
                    #imv tmp users
                    echo "You have successfully deleted the user."
                    sleep 2
                    mainMenu
   fi

 }

我试过了,但它不起作用!是sed问题?

请帮忙。

2 个答案:

答案 0 :(得分:1)

您最好使用built in functionality。 e.g。

:g/^theuserid:/d

答案 1 :(得分:0)

只为了好玩 - 这是你的功课。下次标记它。

#!/bin/bash
IDFILE="./testfile"
function killVogon() {
while read -p 'Enter Vogon-ID (or "q" for return) >' id
do
    case "$id" in
        (q|Q) return;;
    esac
    grep "^0*$id:" "$IDFILE" >/dev/null 2>&1
    case $? in
        (0) ;;
        (1) echo "Although it is infinitely improbable, the '$id' does not exists!"; continue;;
        (*) echo "You're blind and can't see any Vogons around"; sleep 1 ; return;;
    esac
    sed -i '.bak' -e "/^0*$id:/d" "$IDFILE"
    case $? in
        (0) echo "The Vogon is successfully killed"; sleep 1; return;;
        (*) echo "Huh... Marvin, powered with pangalactic gargleblaster is too paranoid now. The Vogon is NOT killed" ;;
   esac
done
}
killVogon