如何使用sed插入包含斜杠的字符串? [英] How to insert strings containing slashes with sed?

查看:37
本文介绍了如何使用sed插入包含斜杠的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个本地开发的 Visual Studio 项目.代码文件必须部署到远程服务器.唯一的问题是它们包含的 URL 是硬编码的.

I have a Visual Studio project, which is developed locally. Code files have to be deployed to a remote server. The only problem are the URLs they contain, which are hard-coded.

该项目包含 URL,例如 ?page=one.为了使链接在服务器上有效,它必须是 /page/one .

The project contains URLS such as ?page=one. For the link to be valid on the server, it must be /page/one .

我决定在部署前用 sed 替换我代码文件中的所有 URL,但我被斜线卡住了.

I've decided to replace all URLS in my code files with sed before deployment, but I'm stuck on slashes.

我知道这不是一个很好的解决方案,但它很简单,可以为我节省很多时间.我必须替换的字符串总数少于 10.必须检查的文件总数约为 30.

I know this is a not a pretty solution, but it's simple and would save me a lot of time. The total number of strings I have to replace is fewer than 10. Total number of files which have to be checked is ~30.

描述我的情况的示例如下:

Example describing my situation is below:

我正在使用的命令:

sed -f replace.txt < a.txt > b.txt

replace.txt 包含所有字符串:

s/?page=one&/pageone/g
s/?page=two&/pagetwo/g
s/?page=three&/pagethree/g

a.txt:

?page=one&
?page=two&
?page=three&

运行 sed 命令后 b.txt 的内容:

Content of b.txt after I run my sed command:

pageone
pagetwo
pagethree

我希望 b.txt 包含的内容:

What I want b.txt to contain:

/page/one
/page/two
/page/three

推荐答案

最简单的方法是在搜索/替换行中使用不同的分隔符,例如:

The easiest way would be to use a different delimiter in your search/replace lines, e.g.:

s:?page=one&:pageone:g

您可以使用任何不属于任一字符串的字符作为分隔符.或者,您可以使用反斜杠将其转义:

You can use any character as a delimiter that's not part of either string. Or, you could escape it with a backslash:

s/\//foo/

/ 替换为 foo.如果您不知道替换字符串中可能出现哪些字符(例如,如果它们是 shell 变量),您可能希望使用转义反斜杠.

Which would replace / with foo. You'd want to use the escaped backslash in cases where you don't know what characters might occur in the replacement strings (if they are shell variables, for example).

这篇关于如何使用sed插入包含斜杠的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆