如何使用sed在文本文件中查找对应位置并更新shell [英] How to use sed to find the corresponding place in a text file and update it shell

查看:37
本文介绍了如何使用sed在文本文件中查找对应位置并更新shell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Book name:author:price:Qty:Qty Sold
==================================
harry potter:james:12.99:197:101
===============================

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

I want to update the QTY which is the value of 197 in this case but i cant seems to be able to update the value with my program please help me as i have just started learning shell programming. Thanks

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

推荐答案

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

Refactored to use grep -q; fix the if idiom; anchor the search to start of line; use read -p instead of a separate echo; capture the price inside the parens so that it's not lost; add the missing repeat in the regex; and add back the separator colon after the new qty value; also, add an else clause so that the function doesn't fail silently.

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
}

这篇关于如何使用sed在文本文件中查找对应位置并更新shell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆