linux - 从文本文件中删除字符串时 Sed 无法与 Linux 一起使用

标签 linux bash sed

<分区>

上一个主题 - https://stackoverflow.com/questions/40808975/overwrite-script-in-bash-shell

我正在做一个大学项目,我们必须创建一个带有删除和恢复选项的回收站。我已经完成了这两个部分,并且恢复选项有效(大部分)。它将已删除文件的位置保存在一个名为 FilePaths 的 txt 文件中,作为将文件恢复到其原始位置时的引用。

我知道将文件位置的副本保存到此文件中会导致问题,因此我必须在 bash 脚本中创建一行以从文本文件中删除特定文件位置字符串。

我知道 sed 可以提供帮助,我可以操纵它来做任何我想做的事情,但问题是它似乎根本没有做任何事情。我什至使用一个简单的“test2”文本文件对其进行了测试,其中包含单词 hello。

sed '/hello/d' test2

这绝对没有任何作用。我已经用双引号试过了,但仍然一无所获,它根本没有从我的 test2 文件中删除“hello”

就恢复功能而言,这是我目前拥有的

#!/bin/sh
#navigate to the Recycle_Bin directory
cd $HOME/Recycle_Bin

#take the string from FilePaths and save it to restore
restore="$(grep "$1" "$HOME/FilePaths")"

#take the string saved in restore and use it as the file's path
filename="$(basename "$restore")"

#remove the string matching restore within FilePaths
sed '/$restore/d' $Home/FilePaths

#set location
location="$(readlink -f "$location")"

#move file to original location
mv -i "$1" "$(grep "$1" "$HOME/FilePaths")"

谁能想出 sed 不起作用的任何原因?我已经搜索了几个小时但找不到任何答案,我可以使用 awk 但我觉得 sed 会使我的代码更简单

最佳答案

您的 sed 命令没有将结果写入任何地方,因此它默认为 stdout。您应该使用 -i 标志来就地编辑文件。

sed -i "/$restore/d" $Home/FilePaths

如果这仍然给您带来问题,您可以使用:

sed -i "s/$restore//g" $Home/FilePaths

其中,如果 $restore 是文件中行的全部内容,将执行相同的操作。

关于linux - 从文本文件中删除字符串时 Sed 无法与 Linux 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40874963/

相关文章:

linux - 使用sed从文本文件中的文件中删除多个文件名

linux - 在没有ssh的情况下在本地服务器上执行脚本

linux - 操作系统存储在磁盘上的什么位置,引导加载程序如何找到它?

git - 用于 Minecraft 服务器备份/版本控制的 Git 替代品

Linux 退出命令什么都不做

linux - bash 脚本 : find and replace multiword string

linux - 如何从 Linux .so 文件中删除未使用的代码?

java - 如何使用 cli 更新配置文件的 ~/.aws/credentials 文件中的 aws key ?

Mysql2创建VIEW时出现语法错误

sed - grep 或 sed 比较两个文件中的数据