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

时间:2021-07-24 16:50:57

how to sed replace whole line with the string as variable ?

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

#!/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

It is storing the variable in RSA but not replacing, not sure what's wrong with sed part.

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

1 个解决方案

#1


2  

You can use the following command.

您可以使用以下命令。

#!/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

I modified as per your requirement to add if not line exists and replace if it exists.

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

#1


2  

You can use the following command.

您可以使用以下命令。

#!/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

I modified as per your requirement to add if not line exists and replace if it exists.

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