开发者

Whats the Vi command to delete a line from a file from a user input?

开发者 https://www.devze.com 2023-03-06 14:16 出处:网络
I have a file and want to delete lines when user enters an ID in UNIX/Vi. The file is called \'users\' and contains:

I have a file and want to delete lines when user enters an ID in UNIX/Vi.

The file is called 'users' and contains:

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

I have used the following function in Vi:

 function deleteRecord()
  {

    echo "Please enter staff ID: "
    read userID

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

    #store staff de开发者_开发百科tails 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

 }

I have tried that but it does not work! Is sed the problem?

Please help.


You're best off using the built in functionality. e.g.

:g/^theuserid:/d


Only for fun - here is your homework. Next time tag it.

#!/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
0

精彩评论

暂无评论...
验证码 换一张
取 消