Sed 更新标题但使用第二列作者作为匹配标准

Sed to update title but using the 2nd column author as a matching criteria

我有这个代码类似于我的另一个问题代码,但这次我试图编辑标题,但使用作者作为标准并单独保留重复项。但是当我 运行 代码时,它与使用标题作为匹配标准并编辑作者的工作方式不同。

我想知道我应该如何纠正这个问题。感谢您的帮助。

例如 文本文件 BookDB.txt 它包含以下内容

Wolverine:Stan Lee:5:1:1
Wolverine:Stan Tan:1:1:1

我想将 Wolverine:Stan Tan 的标题更改为例如 Weapon X。我尝试使用下面的代码,但没有成功。如果我删除 /^$author:/ 他们会改变两者。所以txt文件应该改成

Wolverine:Stan Lee:5:1:1
Weapon X:Stan Tan:1:1:1

代码

  function update_author
{
     echo "Title: "
     read title
     echo "Author: "
     read author
     grep -iqs "$title:$author:" BookDB.txt && echo "Book Found\n"
     echo "New Title: "
     read title_r
     sed -i "/^$author:/ s/$title/$title_r/" BookDB.txt || tee BookDB.txt && echo "Book Author has been updated sucessfully!"
}

将你的最后一个 sed 行更改为

Status="$( sum BookDB.txt )"
sed -i "/^\(${author}\):${title}:/ s//:${title_r}:/" BookDB.txt
if [ "${Status}" = "$( sum BookDB.txt )" ]
 then
   echo "Book Author has no modification for [${author}:${title}]"
 else
   echo "Book Author has been updated sucessfully for [${author}:${title}] !"
 fi

(代码是在批处理模式下编写的,有多个 author/title 可以更改,因此您可以简化 echo return 和检查任何更改的方法)

使用这个,首先你得到标题并将其与作者匹配以使其唯一,然后再切换作者这样我就不会删除每一个可能的匹配项

sed -i "/^$title:$author:/ s/$author/$author_new/" BookDB.txt