用 sed 替换方括号之间的字符串 [英] Replace string between square brackets with sed

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

问题描述

我在文本文件中有一些字符串,如下所示:

I have some strings in a textfile that look like this:

[img:3gso40ßf]

我想把它们替换成普通的 BBCode:

I want to replace them to look like normal BBCode:

[img]

我怎样才能用 sed 做到这一点?我试过这个,但它没有做任何事情:

How can I do that with sed? I tried this one but it doesn't do anything:

sed -i 's/^[img:.*]/[img]/g' file.txt

推荐答案

转义方括号

方括号是元字符:它们有一个POSIX 正则表达式中的特殊含义.如果你的意思是 [] 字面,你需要在你的正则表达式中转义这些字符:

Escape those square brackets

Square brackets are metacharacters: they have a special meaning in POSIX regular expressions. If you mean [ and ] literally, you need to escape those characters in your regexp:

$ sed -i .bak 's/\[img:.*\]/\[img\]/g' file.txt

使用[^]]*代替.*

因为 * 是贪婪的,所以 .* 会捕获比你想要的更多;参见 Jidder 的评论.要解决此问题,请使用 [^]]*,它会捕获直到(但不包括)遇到的第一个 ] 的字符序列.

Use [^]]* instead of .*

Because * is greedy, .* will capture more than what you want; see Jidder's comment. To fix this, use [^]]*, which captures a sequence of characters up to (but excluding) the first ] encountered.

$ sed -i .bak 's/\[img:.[^]]\]/\[img\]/g' file.txt

您是否使用了不正确的 sed -i 语法?

(感谢 ja 他的评论.)

根据您使用的 sed 的风格,您可能被允许使用 sed -i 而无需指定任何 参数,如

Depending on the flavour of sed that you're using, you may be allowed to use sed -i without specifying any <extension> argument, as in

$ sed -i 's/foo/bar/' file.txt

但是,在 sed 的其他版本中,例如 Mac OS X 附带的版本,sed -i 需要 mandatory 参数,如

However, in other versions of sed, such as the one that ships with Mac OS X, sed -i expects a mandatory <extension> argument, as in

$ sed -i .bak 's/foo/bar/' file.txt

如果省略该扩展参数(.bak,此处),则会出现语法错误.您应该查看 sed 的手册页以确定该参数是可选的还是必需的.

If you omit that extension argument (.bak, here), you'll get a syntax error. You should check out your sed's man page to figure out whether that argument is optional or mandatory.

有没有办法告诉sed 冒号后面总是有 8 个随机字符?

Is there a way to tell sed that there are always 8 random characters after the colon?

是的,有.如果冒号和右方括号之间的字符数始终相同(此处为 8 个),则可以使命令更具体:

Yes, there is. If the number of characters between the colon and the closing square bracket is always the same (8, here), you can make your command more specific:

$ sed -i .bak 's/\[img:[^]]\{8\}\]/\[img\]/g' file.txt

示例

# create some content in file.txt
$ printf "[img:3gso40ßf]\nfoo [img:4t5457th]\n" > file.txt

# inspect the file
$ cat file.txt
[img:3gso40ßf]
foo [img:4t5457th]

# carry out the substitutions
$ sed -i .bak 's/\[img:[^]]\{8\}\]/\[img\]/g' file.txt

# inspect the file again and make sure everything went smoothly
$ cat file.txt
[img]
foo [img]

# if you're happy, delete the backup that sed created
$ rm file.txt.bak

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

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