1

我正在使用 Bourne Shell Script 构建学生数据库。我需要能够更新之前输入到文件中的一行数据,但我无法弄清楚如何做到这一点。这是我尝试过的:

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

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

   if [ "$updateNumber" -gt "1" ]
   then
          echo "ambiguous input"
   elif [ ! grep -iq "$updateInput" database.txt ]
   then
           echo "record not found"
   else
           lineNumber=$(grep -ni $updateInput database.txt)

           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 first last
           echo "age ($age): \c"
           read age
           echo "course-1 ($course1): \c"
           read course1
           while ! fgrep -iwq "$course1" $FILE 
           do
                   echo "course does not exist"
                   echo "course-1: \c"
                   read course1  
           done
           echo "course-2 ($course2): \c"
           read course2
           while ! fgrep -iwq "$course2" $FILE 
           do
                   echo "course does not exist"
                   echo "course-2: \c"
                   read course2  
           done
   fi

但这显然根本没有更新文件。我只是不确定如何采用特定的行并更改它的数据。

另外,我的 elif 语句不起作用,我想知道我做错了什么-.- 只是应该说,如果找不到输入的名称,则打印出找不到记录。

感谢大家。我是 Bourne Shell Script 的新手,我在尝试让它工作时遇到了一些真正的麻烦。

4

2 回答 2

0

如果您想更新文件中的一行,您的示例不是很清楚。您可以使用命令“sed”,它对文件执行查找/替换。请查看其 unix man 的用法。

IE:

sed -i 's/day/night/g' file.txt 

将 file.txt 中的“day”替换为“night”

于 2013-04-10T23:44:18.500 回答
0

您可以使用sed带有 inplace 标志的命令-i——它比ed. 例如,如果您想更改文件的第 5 行,$first|$last|$course那么请执行

sed -i '' -e s "5s/.*/$first|$last|$course/" database.txt

附带说明一下,您可以使用awk它轻松地从数据库中提取数据和构建报告。

于 2014-09-13T07:29:25.860 回答