使用 Sed 从文本文件中删除一行

发布于 2024-12-03 19:42:28 字数 178 浏览 0 评论 0原文

我正在尝试使用 sed 从文件 /root/.ssh/authorized_keys 中删除给定的行 $2 。这是我正在运行的命令,不幸的是,它没有删除该行。知道我做错了什么吗?

 sed -i '/$2/d' /root/.ssh/authorized_keys

I am trying to remove a given line $2 from the file /root/.ssh/authorized_keys using sed. Here is the command I am running, unfortunately, its not deleting the line. Any idea what I'm doing wrong?

 sed -i '/$2/d' /root/.ssh/authorized_keys

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

守望孤独 2024-12-10 19:42:28

$2 不会被单引号内的值替换。应该使用双引号。

$2 won't be replaced with its value inside single quotes. Should work with double quotes.

不必了 2024-12-10 19:42:28

按照 Glenn Jackman 的建议发布非 sed 答案。 Tom Zych 已经发布了基本的“正确答案”;另请注意 Holygeek 的评论。

mv authorized_keys authorized_keys~
fgrep -v "$2" authorized_keys~ >authorized_keys

如果没有临时文件,您可能也能过得去,但我不在电脑前,所以我现在要谨慎行事。

Posting a non-sed answer as suggested by Glenn Jackman. The basic "right answer" was already posted by Tom Zych; note also the comment by holygeek.

mv authorized_keys authorized_keys~
fgrep -v "$2" authorized_keys~ >authorized_keys

You could probably get by without the temporary file but I'm not at my computer so I'm playing it safe for now.

人事已非 2024-12-10 19:42:28

您还可以使用外壳

while read -r line
do
   case "$line" in 
     *"$2"* ) continue;;
     * ) echo "$line" ;;
   esac
done < /root/.ssh/authorized_keys > tempfile
mv tempfile /root/.ssh/authorized_keys

You can also use the shell

while read -r line
do
   case "$line" in 
     *"$2"* ) continue;;
     * ) echo "$line" ;;
   esac
done < /root/.ssh/authorized_keys > tempfile
mv tempfile /root/.ssh/authorized_keys
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文