0

I'm trying to update a file in Bourne Shell. The user inputs a name and then is prompted to change the persons name, age and courses. Here's part of the code I've written:

  echo "please enter the name: \c"
   read updateInput

   updateNumber=$(grep -cwi "$updateInput" database.txt)
   updateRecord=$(grep -i "$updateInput" database.txt)

   test=$(! grep -i "$updateInput" database.txt)

   if [ "$updateNumber" -gt "1" ]
   then
          echo "ambiguous input"
   elif [ "$updateRecord" = "" ]
   then
           echo "record not found"
   else
           lineNumber=$(grep -ni $updateInput database.txt | cut -f1 -d:)

           grep -i $updateInput database.txt > tmp
           read first last age course1 course2 < tmp

           echo "record found, enter new value now:"
           echo "name ($first $last): \c" 
           read uFirst uLast
           if [ "$uFirst" != "" ]
           then
                   sed "$lineNumber s/$first/$uFirst/" database.txt
           fi
           if [ "$uLast" != "" ]
           then
                   sed "$lineNumber s/$last/$uLast/g" database.txt
           fi

When run, sed outputs the correct output with the right things changed, but it doesn't actually update the database file at all. I've tried googling all sorts of things, but nothing is working. If someone could point me in the right direction, that would be awesome. Thanks so much :)

4

1 回答 1

2

如果这是 GNU sed,您可以使用该-i选项来编辑文件:

sed -i "$lineNumber s/$first/$uFirst/" database.txt

否则,您需要将 sed 输出捕获到一个临时文件中,然后将其复制到原始文件上。

于 2013-03-29T19:14:25.350 回答