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

标签 bash shell sed user-input

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

我尝试了这段代码

我做了什么:

    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

然后,如果出现问题或者您删除了错误的书,则可以轻松回滚。此外,这还可以与 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/

相关文章:

shell - 识别文件夹的构建类型

linux - 提取值与特定模式匹配的列

linux - 如果存在另一行,则 Bash 替换行

linux - 在 bash 中使用/home/directory 从所有用户创建菜单

linux - 比较两个文件 diff awk else

linux - 跳过 "find"输出中的字符

bash - 为什么带有不带引号的变量的 glob 会扩展到所有文件?

bash - 我想使用并行 ssh 在多个服务器上运行 bash 脚本,但它简单地打印 echo 语句

mysql - 在插入表之前应用正则表达式从 .csv 加载数据

linux - 这个命令在做什么? sed