string - 用 sed 替换方括号之间的字符串

标签 string replace sed brackets

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

[img:3gso40ßf]

我想将它们替换为正常的 BBCode:
[img]

我怎样才能用 sed 做到这一点?我试过这个,但它没有做任何事情:
sed -i 's/^[img:.*]/[img]/g' file.txt

最佳答案

转义那些方括号

方括号是metacharacters : 他们有一个 special meaning in POSIX regular expressions .如果您的意思是 []从字面上看,您需要在正则表达式中转义这些字符:

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

使用 [^]]*而不是 .*
因为 *很贪心,.*会捕捉到比你想要的更多的东西;见 Jidder's comment .要解决此问题,请使用 [^]]* ,它捕获直到(但不包括)第一个 ] 的字符序列遭遇。

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

您是否使用了错误的 sed -i句法?

(感谢 j.a. 提供 his comment。)

sed的口味而定您正在使用的,您可能会被允许使用 sed -i不指定任何 <extension>论证,如

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

但是,在 sed 的其他版本中,例如 Mac OS X 附带的那个,sed -i期望强制<extension>论证,如

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

如果省略该扩展参数(这里是 .bak ),则会出现语法错误。您应该查看您的 sed的手册页来确定该参数是可选的还是强制性的。

匹配特定数量的字符

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



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

$ 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

关于string - 用 sed 替换方括号之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27696805/

相关文章:

javascript - 将字符串添加到 href ="javascript"中

javascript - 使用javascript删除部分字符串

string - 从内存中的字符串加载node.js模块

JavaScript:替换包含换行符的字符串

python - 使用 Python 只保留字符串中的某些字符?

bash - 设置 svn :ignore recursively for a directory structure

MySQL使用字符串函数查找列中的最后一位数字

javascript - HTML 输入 ="file"按钮到文本

bash - 在 bash 脚本中转义 sed 字符串

regex - sed-如何使用sed提取IP地址?