首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >更新文本文件中特定行中的特定字段

更新文本文件中特定行中的特定字段
EN

Stack Overflow用户
提问于 2013-07-27 11:28:08
回答 1查看 910关注 0票数 0

下面是一个代码,我可以更新我的书的数量。但我似乎无法做到这样才能更新我的其他东西,如书名、作者、价格等。下面是代码:

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

我的数据库会是这样的:

代码语言:javascript
复制
Harry Potter - The Half Blood Prince:J.K Rowling:40.30:10:50
The little Red Riding Hood:Dan Lin:40.80:20:10
Harry Potter - The Phoniex:J.K Rowling:50.00:30:20
Harry Potter - The Deathly Hollow:Dan Lin:55.00:33:790
Little Prince:The Prince:15.00:188:9
Lord of The Ring:Johnny Dept:56.80:100:38
Three Little Pig:Andrew Lim:89.10:290:189
All About Ubuntu:Ubuntu Team:76.00:55:133
Catch Me If You Can:Mary Ann:23.60:6:2
Happy Day:Mary Ann:12.99:197:101
haha:gaga:1:10:1

那么,我怎样才能改变某些领域,比如,当我选择图书名,“指环王”,作者约翰尼·德普,我可以把书名改成“国王之王”吗?

代码语言:javascript
复制
Lord of The King:Johnny Dept:56.80:100:38
EN

回答 1

Stack Overflow用户

发布于 2013-07-27 12:39:09

user1146332一样,我也建议改用一种更强大的语言。这里有一个使用珀尔的例子。它使用模块Getopt::Long读取参数,并遍历匹配行的文件。

这似乎是可行的,但应该由您对错误进行更好的检查,例如,在正则表达式中使用bookauthor变量之前,必须定义它们。

还有一件事,我使用带有冒号的split()来提取字段,我不知道如何处理带有冒号的图书,但是在这种情况下,您需要一个额外的模块来解析CSV,比如Text::CSV,或者用更好的split表达式来更努力地工作。

代码语言:javascript
复制
#!/usr/bin/env perl

use strict;
use warnings;
use Getopt::Long;

my ($book, $author, $newbook, $quantity);

my $r = GetOptions(
        q|book=s| => \$book,
        q|author=s| => \$author,
        q|newbook=s| => \$newbook,
        q|quantity=i| => \$quantity,
) or die;

open my $fh, '<', $ARGV[0] or die;

while ( <$fh> ) { 
        chomp;
        my @f = split /:/;
        next if @f < 5;
        if ( $f[0] =~ m/(?i)\Q$book\E/ &&
             $f[1] =~ m/(?i)\Q$author\E/ ) { 
                $f[0] = defined $newbook ? $newbook : $f[0];
                $f[3] = defined $quantity ? $quantity : $f[3];
                printf qq|%s\n|, join q|:|, @f; 
                next;
        }   

        printf qq|%s\n|, $_; 
}

一个例子是:

代码语言:javascript
复制
perl script.pl --book="lord of the ring" --author=dep --newbook="Lord of the King" --quantity=99 infile

产量:

代码语言:javascript
复制
Harry Potter - The Half Blood Prince:J.K Rowling:40.30:10:50
The little Red Riding Hood:Dan Lin:40.80:20:10
Harry Potter - The Phoniex:J.K Rowling:50.00:30:20
Harry Potter - The Deathly Hollow:Dan Lin:55.00:33:790
Little Prince:The Prince:15.00:188:9
Lord of the King:Johnny Dept:56.80:99:38
Three Little Pig:Andrew Lim:89.10:290:189
All About Ubuntu:Ubuntu Team:76.00:55:133
Catch Me If You Can:Mary Ann:23.60:6:2
Happy Day:Mary Ann:12.99:197:101
haha:gaga:1:10:1
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17897231

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档