gpt4 book ai didi

Bash 脚本 - 如何从文本文件中删除行/字?

转载 作者:行者123 更新时间:2023-11-29 09:47:31 25 4
gpt4 key购买 nike

用户输入书名和作者(从文本文件)后,我无法从文本文件中删除一行

我试过这段代码

我做了什么:

    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!

(Desired Output 中的书籍和作者姓名只是示例)

来自

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

然后,如果出现问题或您删除了错误的书,回滚很容易。此外,这将适用于 GNU 之外的其他 awk。

或者,您可以像这样使用 grep:

cp BookDB.txt BookDB.txt~
grep -vxF "$title $name" BookDB.txt~ > BookDB.txt

其中 -x 告诉 grep 仅当匹配是整行时才匹配,而 -F 告诉它将模式作为固定字符串而不是正则表达式。

关于Bash 脚本 - 如何从文本文件中删除行/字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27987545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com