用sed替换整行变量

时间:2020-05-20 07:42:16

标签: unix sed

文件内容

something
OIDCRedirectURI http://abc-mt.tc.ac.com/newredirect
something

sed命令已尝试

URL='xyz-new.com' #This will be forming at run time

sed -i 'abc /c\ OIDCRedirectURI $URL/newredirect' /etc/httpd/conf.d/proxy.conf

基本上我想用新的URL替换给定的URL。

但是它将替换为$ URL。

有指针吗?

2 个答案:

答案 0 :(得分:1)

假定新的URL保存在外壳变量中:$URL 这种单线可能会帮助您:

sed -i "s@\(^OIDCRedirectURI \).*@\1$URL/newredirect@" file

在您的示例中,URL不具有协议,例如HTTP或https。如果要“重用”“旧” URL中的协议前缀,可以将其添加到捕获组:

sed -i "s@\(^OIDCRedirectURI http[^/]*//\).*@\1$URL/newredirect@" file

只是为了表明它正在工作:

kent$  cat /tmp/test/f
something
OIDCRedirectURI http://abc-mt.tc.ac.com/newredirect
something

kent$  URL='this.is.new.url'

kent$  sed -i "s@\(^OIDCRedirectURI http[^/]*//\).*@\1$URL/newredirect@" /tmp/test/f

kent$  cat /tmp/test/f
something
OIDCRedirectURI http://this.is.new.url/newredirect
something

答案 1 :(得分:0)

我个人不会使用sed。

#!/bin/sh -x

mystring="OIDCRedirectURI http://abc-mt.tc.ac.com/newredirect"
redir=$(echo -e "${mystring}" | cut -d' ' -f1)
oldurl=$(echo -e "${mystring}" | cut -d' ' -f2)
newurl="http://xyz-new.com"

echo -e "${redir} ${newurl}"

当然,您可能希望循环使用此类条目的列表来执行此操作,但这并不难。您只需要将旧的URL和新的URL放入两个堆栈文件中,并确保它们在每个文件中的顺序正确。

相关问题