【问题标题】:Updating fields in text file, shell bash更新文本文件中的字段,shell bash
【发布时间】:2013-01-20 09:25:23
【问题描述】:

我有一个文本文件。

文本文件中的信息是

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!"

数量无法更新,因为我有点丢失了价格信息。如果我立即将一本新书添加到存储价格的程序中,我可以编辑数量,但对于其他书籍,无法编辑可用数量。

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

【问题讨论】:

    标签: bash shell


    【解决方案1】:

    您可以使用的更新数量:

    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!"
    

    【讨论】:

    • 我是 bash shell 脚本的新手。请问 ([^:]+) 是做什么的?还有 [^:] , \1 是否取 ([^:]+) 的值?
    • 1) ([^:]+) 是正则表达式,它匹配包含多个字符且所有这些字符不是':' 的字符串。 2) 是的。
    • 1.5) [^:] 是正则表达式,匹配除':' 之外的任何字符。
    猜你喜欢
    • 2014-04-28
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    • 2018-07-13
    • 2012-07-13
    • 1970-01-01
    相关资源
    最近更新 更多