用 shell 脚本中另一个文件中存在的 url 替换文件中的字符串

Replace string in a file with url present in another file in shell script

我想尝试使用 sed 命令将文件中的字符串替换为另一个文件中存在的 url。 例如... 设 url.txt 为包含 url:

的文件

和 demo.txt 包含 Replace_Url 我使用的 sed 命令是:

sed -i "s/Replace_Url/$(sed 's:/:\/:g' url.txt)/" demo.txt

没有错误但是字符串没有被替换..

sed -i "s@Replace_Url@$(<url.txt)@" demo.txt 有效

很难用 sed 稳健地完成这项工作,因为 sed 不支持文字字符串操作(参见 ),所以只需使用 awk 代替,例如:

awk -v old='Replace_Url' '
    NR==FNR { new=[=10=]; next }
    s=index([=10=],old) { [=10=] = substr([=10=],1,s-1) new substr([=10=],s+length(old)) }
    { print }
' url.txt demo.txt