如何使用 sed 编辑特定字段?

问题描述 投票:0回答:1

我在使用下面提供的代码中的modify_record函数时遇到了麻烦。我可以使用 awk,但我的老师告诉我们使用 sed。有人可以帮忙吗?

menu() {
    echo "choose one of the following options: \n"
    echo "1) create a student database"
    echo "2) view a student database"
    echo "3) insert a student record"
    echo "4) delete a student record"
    echo "5) modify a record"
    echo "6) display result"
    echo ""
}


create_db() {
    echo "creating a student database..."
    touch student.db
    echo "created a student database."
}


view_db() {
    echo -e "opening database... \n"
    cat student.db
}

insert_record() {
    echo -e "enter roll number: \c"
    read roll
    echo -e "enter name of student: \c"
    read name
    echo -e "enter marks of subject 1: \c"
    read sub1
    echo -e "enter marks of subject 2: \c"
    read sub2
    echo -e "enter marks of subject 3: \c"
    read sub3
    
    echo "$roll|$name|$sub1|$sub2|$sub3" >> student.db
    
}

delete_record() {
    echo -e "enter roll number whose info is to be deleted: \c"
    read roll
    grep -iv $roll student.db > temp.db && mv temp.db student.db
}

modify_record() {
    echo -e "enter roll no. whose info is to be modified: \c"
    read roll
    #echo -e "enter name: "
    #read temp_name
    echo -e "enter sub1 marks: \c"
    read newsub1
    echo -e "enter sub2 marks: \c"
    read newsub2
    echo -e "enter sub3 marks: \c"
    read newsub3

    sed -i "s/^$roll|\([^|]*\)|[^|]*|[^|]*||[^|]*\$/&\1|$newsub1|\2|$newsub2|\3|$newsub3/" student.db

 
    
}

calc_avg() {
    echo "enter roll no. whose average is to be calculated: \c"
    read rollno
    x=`grep $rollno student.db | cut -d'|' -f3`

    y=`grep $rollno student.db | cut -d'|' -f4`
    
    z=`grep $rollno student.db | cut -d'|' -f5`
    
    sum=`expr $x + $y + $z`
    average=`expr $sum / 3`
    # echo -e "average: $average\n"
    echo -e "average: $average\n"
}


while : 
do
    menu
    read -p "enter your choice: " choice
    
    case $choice in
    1) create_db ;;
    2) view_db ;;
    3) insert_record ;;
    4) delete_record ;;
    5) modify_record ;;
    6) calc_avg ;;
    7) break ;;
    *) echo "invalid choice"
    esac
    
done

运行此代码时创建的数据库如下所示:

rollno|名称|sub1|sub2|sub3

modify_record() 中的 sed 行不是替换主题标记,而是将它们随机插入到其他字段之间。我查找了其他解决方案并尝试复制他们的实现,但没有成功。

linux shell sh
1个回答
0
投票

以下序列精确替换由“|”分隔的字段 3,4,5性格:

sed -i "s/[^|]*/$newsub1/3" student.db
sed -i "s/[^|]*/$newsub2/4" student.db
sed -i "s/[^|]*/$newsub3/5" student.db
© www.soinside.com 2019 - 2024. All rights reserved.