关于用 sed 替换字符串 [英] About replacing string with sed

查看:40
本文介绍了关于用 sed 替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 < 替换所有的 \r\nbr/> 在一个文档中,我正在尝试使用下面的脚本

I'd like to replace all the \r\n with < br/ >in a document, and I'm trying this see script below

# sed -i 's/\r\n/<br/>' ~/xxd/*

但是我又得到了这个错误

however i got this error back

sed:-e 表达式 #1,字符 12:`s' 的未知选项

sed: -e expression #1, char 12: unknown option to `s'

我该如何解决这个问题?

How do i solve this problem?

谢谢!

推荐答案

你的问题是你的替换字符串中有 / 分隔符,所以 sed 假设这是替换结束,并且它后面的 > 是一个标志.

Your problem is that you have the / separator in your replacement string so sed is assuming that's the end of your replacement, and that the > following it is a flag.

如果你的 sed 足够现代,只需使用一个不同的分隔符,一个不是在替换字符串中的:

If your sed is modern enough, just use a different separator character, one that's not in the replacement string:

pax$ echo hello | sed -e 's/e/<br />/'
sed: -e expression #1, char 9: unknown option to `s'

pax$ echo hello | sed -e 's?e?<br />?'
h<br />llo

或者,您可以转义有问题的字符,但我尽量避免这种情况,因为它往往会导致过度锯齿的 sed 命令,例如 /\/\/\/\/\/\.

Alternatively, you can escape the offending character but I try to avoid that since it tends to lead to overly sawtooth sed commands like /\/\/\/\/\/\.

您可能需要注意的另一件事是尝试在正则表达式中使用 \n ,因为 sed 无论如何都在行上运行.如果您的目的只是删除回车符并插入 HTML 换行符,那么以下 sed 命令可能会更好:

The other thing you may want to watch out for is trying to use \n in your regex since sed operates on lines anyway. If your intent is to just strip carriage returns and insert HTML line breaks, then the following sed command may be better:

s?\r$?<br />?

这篇关于关于用 sed 替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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