【问题标题】:How to use sed to find the corresponding place in a text file and update it shell如何使用sed在文本文件中查找对应位置并更新shell
【发布时间】:2013-07-24 19:42:56
【问题描述】:
Book name:author:price:Qty:Qty Sold
==================================
harry potter:james:12.99:197:101
===============================

我想更新 QTY,在这种情况下是 197 的值,但我似乎无法用我的程序更新该值,请帮助我,因为我刚刚开始学习 shell 编程。谢谢

function update_qty_available
{
grep -c "$title:$author" BookDB.txt > /dev/null # Look for a line with matching values

if [ $? == 0 ]; 
then # If found then offer to change Qty
echo "Update Qty to what?"
read newQty
sed -i "s/\($title:$author\):[^:]:[^:]*:/\1:$newQty/" BookDB.txt
    echo "Book's Qty has been updated successfully!"
fi

【问题讨论】:

  • 您应该考虑使用 awk。或者一个实际的数据库。 (或实际的编程语言。)
  • @IgnacioVazquez-Abrams 这是我任务的一部分,我设法更新了价格,但我似乎无法更新数量。
  • 完成这项繁重的工作后,学习如何在 awk 中完成。
  • 我以为 J.K.罗琳写了哈利波特的书。
  • 谢谢你们,你们救了我的命!

标签: shell replace sed


【解决方案1】:

以下是您对awk 的处理方式:

script.awk的内容:

BEGIN {
    FS=OFS=":"
    printf "Enter the book's name: "
    getline name < "-"
    printf "Enter author's name: "
    getline author < "-"
    printf "Enter new quantity: "
    getline newQty < "-"
}

$1==name && $2==author { $4=newQty }1

运行:

$ cat BookDB.txt 
Book name:author:price:Qty:Qty Sold
==================================
harry potter:james:12.99:197:101
===============================

$ awk -f script.awk BookDB.txt 
Enter the book's name: harry potter
Enter author's name: james
Enter new quantity: 5000
Book name:author:price:Qty:Qty Sold
==================================
harry potter:james:12.99:5000:101
===============================

【讨论】:

    【解决方案2】:

    重构为使用grep -q;修复if 成语;将搜索锚定到行首;使用read -p 而不是单独的echo;捕获括号内的价格,以免丢失;在正则表达式中添加缺少的重复;并在新的数量值后添加分隔冒号;另外,添加一个else 子句,这样函数就不会静默失败。

    function update_qty_available
    {
        if grep -q "^$title:$author:" BookDB.txt
        then
            read -p "Update Qty to what?" newQty
            sed -i "s/^\($title:$author:[^:]*\):[^:]*:/\1:$newQty:/" BookDB.txt
            echo "Book's Qty has been updated successfully!"
        else
            echo "$0: BookDB.Txt: no '$title' by '$author'" >&2
        fi
    }
    

    【讨论】:

    • 嗨,你给我的代码可以用,但是 newQty 也可以代替价格来解决这个问题?
    • 我已经在编辑中修复了这个问题,还修复了其他几个问题。
    • 你能给我解释一下这行吗? sed -i "s/^($title:$author:[^:]*):[^:]*:/\1:$newQty:/" BookDB.txt
    • 嗯?它几乎是从您的原始脚本中逐字复制(以一些小修复为模)。如果您有新问题,我的建议是发布一个新问题,而不是在这里跟进,基本上只有您和我会看到它。
    • @tripleeee 我的意思是,如果我决定在该行中更新书名该怎么办?
    【解决方案3】:

    您在第一个字符类之后缺少一个星号。并且不要忘记扩展组。

    【讨论】:

    • 神秘,但准确。
    猜你喜欢
    • 2011-07-03
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    • 2012-02-14
    • 2020-01-20
    • 1970-01-01
    • 2018-05-09
    • 2011-07-06
    相关资源
    最近更新 更多