用户输入书名和作者(从文本文件中)后,我无法从文本文件中删除一行
我尝试了这段代码
我做了什么:
function remove_book
{
echo "Title: "
read title
echo "Author: "
read name
echo $title $name < BookDB.txt
echo "Book $title by $name successfully removed!"
sed '/pattern to match/d' ./BookDB.txt
#echo "testing remove"
}
但是然后,它显示了这一点
即使这样显示,也实际上并未将其从文件中删除。
Title:
The Hobbit
Author:
J.R.R. Tolkien
The Hobbit J.R.R. Tolkien
Book The Hobbit by J.R.R. Tolkien successfully removed!
Harry Potter and the Deathly Hallows J.K. Rowling
The Maze Runner James Dashner
Life Without Limits Nick Vujicic
The Hobbit J.R.R. Tolkien
所需的输出:
1) Add new book
2) Remove existing book info
3) Update book info and quantity
4) Search for book by title/author
5) Process a book sold
6) Inventory summary report
7) Quit
Please enter your option: 2
Title : Biography of Crocodile Dundee
Author : Crox Swamplund
Error! Book does not exists!
1) Add new book
2) Remove existing book info
3) Update book info and quantity
4) Search for book by title/author
5) Process a book sold
6) Inventory summary report
7) Quit
Please enter your option: 2
Title : C++ for dummies
Author : Edward Scissorhands
Book Title ‘C++ for dummies’ removed successfully!
(“期望的输出”中的书名和作者的名字仅是示例)
从
Harry Potter and the Deathly Hallows J.K. Rowling
The Maze Runner James Dashner
Life Without Limits Nick Vujicic
The Hobbit J.R.R. Tolkien [remove one line, like this Hobbit book]
到
Harry Potter and the Deathly Hallows J.K. Rowling
The Maze Runner James Dashner
Life Without Limits Nick Vujicic
如何删除一行?用户输入标题和作者姓名后?帮帮我,谢谢!:)
请勿使用sed执行此操作。在某个时候,某处某人会写一本书,标题为“好时/坏时”或“ Ca $ h ca $ h ca $ h !!! 1!在业余时间赚钱!” 或“您一直想知道(从来不敢问)”的内容,而sed会把它搞砸了,因为特殊字符对其模式匹配引擎具有意义。
您可以使用GNU awk做到这一点,如下所示:
awk -i inplace -v title="$title" -v author="$name" '$0 != title " " author' BookDB.txt
这将从文件中选择所有与行的内容不完全相同的行,$title
然后是一个空格,然后是的内容$name
。由于shell变量不会被替换为awk代码,而是通过awk的-v
参数传递的,因此不会对特殊字符进行任何解释。
另外:您确定要就地执行此操作吗?我喜欢保留备份,以防操作出错。喜欢
cp BookDB.txt BookDB.txt~
awk -v title="$title" -v author="$name" '$0 != title " " author' BookDB.txt~ > BookDB.txt
然后,如果出现问题或您删除了错误的书,则回滚很容易。此外,这将与其他Aks一起使用,而不是GNU的awks。
另外,您可以像这样使用grep:
cp BookDB.txt BookDB.txt~
grep -vxF "$title $name" BookDB.txt~ > BookDB.txt
-x
仅当匹配项是整行时,where才告诉grep进行匹配,并-F
告诉其将模式作为固定字符串而不是正则表达式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句