下面是一个代码,我可以用它来更新我的书的数量。但我似乎做不到,所以我可以更新我的其他东西,比如书名、作者、价格等。 继承人的代码:
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
我的数据库是这样的:
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
那么我如何更改某些字段,例如当我选择书名 Lord of the ring 作者 johnny Dept 时,我可以将书名更改为 maybe lord of the kings 吗?
Lord of The King:Johnny Dept:56.80:100:38
最佳答案
像user1146332,我也建议换一种更强大的语言。这是一个使用 perl 的例子.它使用模块 Getopt::Long
来读取参数并循环遍历文件以找到匹配的行。
这似乎可行,但您需要更好地检查错误,例如,book
和 author
变量在正则表达式。
还有一件事,我使用带冒号的 split()
来提取字段,我不知道你如何处理一本名字中有冒号的书,但在那种情况下你需要一个用于解析 CSV 的附加模块,例如 Text::CSV
或使用更好的 split
表达式进行更激烈的斗争。
#!/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|, $_;
}
一个例子:
perl script.pl --book="lord of the ring" --author=dep --newbook="Lord of the King" --quantity=99 infile
产量:
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
关于linux - 更新特定行中文本文件中的特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17897231/