linux - 如何用字符串作为变量sed替换整行?

标签 linux bash shell awk sed

如何使用 sed 将整行替换为字符串作为变量?

#!/bin/bash
ssh $1 ssh-keyscan -t rsa $1 > /tmp/$1
RSA=$(cat /tmp/$1)
echo $RSA
sed -i 's:'^"$1".*':'"$RSA"':' /etc/ssh/ssh_known_hosts
cat /etc/ssh/ssh_known_hosts | grep $1

它是将变量存储在 RSA 中而不是替换,不确定 sed 部分有什么问题。

最佳答案

您可以使用以下命令。

#!/bin/bash
ssh $1 ssh-keyscan -t rsa $1 > /tmp/$1
RSA=$(cat /tmp/$1)
echo $RSA
sed -i -e "/$1/ d" -e "/^$1/ a $RSA" /etc/ssh/ssh_known_hosts
cat /etc/ssh/ssh_known_hosts | grep $1

我根据您的要求进行了修改,如果行不存在则添加,如果存在则替换。

关于linux - 如何用字符串作为变量sed替换整行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46582038/

相关文章:

c++ - vkGetPhysicalDeviceQueueFamilyProperties 段错误

linux - 将字符串转换为 bash 参数

linux - 用于在千个文件中搜索错误代码然后在文本文件中打印计数的 Unix shell 脚本

bash - 此 bash 命令在 Makefile 中未正确运行

bash - 在一个命令中追加或创建文件?

bash - 我如何在golang中运行shell命令

linux - 将 bash 脚本添加到路径

ruby - 为什么crontab不能用ruby?

linux - 为什么别名在/etc/profile 中不可用?

bash - ps辅助: shows the same script multiple times