更新文本文件中的字段,shell bash

更新文本文件中的字段,shell bash,bash,shell,Bash,Shell,我有一个文本文件 文本文件中的信息是 Book1:Author1:10.50:50:5 Book2:Author2:4.50:30:10 第一个是书名,第二个是作者姓名,第三个是价格,第四个是数量,第五个是销售量 我试图更新价格,但它在以下情况下运行良好: read -p $'New Price: ' newPrice sed "s/${Title}:${Author}:[^:]\+/${Title}:${Author}:${newPrice}/g" BookDB.txt > tempB

我有一个文本文件

文本文件中的信息是

Book1:Author1:10.50:50:5
Book2:Author2:4.50:30:10
第一个是书名,第二个是作者姓名,第三个是价格,第四个是数量,第五个是销售量

我试图更新价格,但它在以下情况下运行良好:

read -p $'New Price: ' newPrice
sed "s/${Title}:${Author}:[^:]\+/${Title}:${Author}:${newPrice}/g" BookDB.txt > tempBook.txt
mv -f tempBook.txt BookDB.txt
echo "Book price updated!"
当我退出程序并添加代码以更新数量时,使用:

read -p $'New Quantity: ' newQty
sed "s/${Title}:${Author}:${Price}:[^:]\+/${Title}:${Author}:${Price}:${newQty}/g" BookDB.txt > tempBook.txt
mv -f tempBook.txt BookDB.txt
echo "Book quantity updated!"
数量无法更新,因为我丢失了一些价格信息。如果我立即在存储价格的程序中添加一本新书,我可以编辑数量,但对于其他书籍,无法编辑可用数量


有人能帮忙吗?我想知道我是否可以提取/存储这本书的价格值。

对于更新数量,您可以使用:

read -p $'New Quantity: ' newQty
sed -re "s/${Title}:${Author}:([^:]+):[^:]+/${Title}:${Author}:\1:${newQty}/g" BookDB.txt > tempBook.txt
mv -f tempBook.txt BookDB.txt
echo "Book quantity updated!"

我不熟悉bashshell脚本。我可以问一下([^:][+)做什么吗?而且[^:],\1是否接受([^::]+)?1)
([^::]+)
的值是regexp,它匹配包含多个字符的字符串,并且所有这些字符不是
:'
。2) 是的。1.5)
[^::][/code>是regexp,它匹配除
':'
之外的任何字符。