繁体   English   中英

使用 sed 和 regex 替换 OSX 和 Linux 上的文本

[英]Using sed with regex to replace text on OSX and Linux

我正在尝试使用正则表达式用sed替换文件中的一些字符串。 更复杂的是,这是在需要在osxlinux上工作的 Makefile 脚本中完成的。

具体来说,在file.tex我想替换

\subimport{chapters/}{xxx}

\subimport{chapters/}{xxx-yyy}

xxxyyy只是示例文本。)

请注意, xxx可以包含任何字母、数字和_ (下划线),但实际上正则表达式可以简单地匹配括号内的任何内容。 有时在\\subimport...之前的行开头有一些空格。

正在搜索的字符串的设计需要大量转义(当使用正则表达式搜索时),我猜测其中的某个地方是我的错误。

这是我迄今为止尝试过的:

sed -i'.bak' -e 's/\\subimport\{chapters\/\}\{xxx\}/\\subimport\{chapters\/\}\{xxx-yyy\}/g' file.tex
# the -i'.bak' is required so SED works on OSX and Linux
rm -f file.tex.bak # because of this, we have to delete the .bak files after

当我构建包含此脚本的 Makefile 时,这会导致RE error: invalid repetition count(s)

我想我的问题的一部分是, -E的选项sed是不可用的osx版本的sed 事实证明,当使用-E选项时,应该转义的东西更少(请参阅对我的问题的评论)。

POSIX-ly:

sed 's#^\(\\subimport{chapters/}{[[:alnum:]_]\+\)}$#\1-yyy}#'
  • #被用作参数隔板seds (换人)

  • \\(\\\\subimport{chapters/}{[[:alnum:]_]\\+\\)是捕获的组,包含直到最后}所需的所有内容,前面是一个或多个字母、数字和下划线

  • 在替换中,第一个捕获的组后跟所需的字符串,以}

例子:

$ sed 's#^\(\\subimport{chapters/}{[[:alnum:]_]\+\)}$#\1-yyy}#' <<<'\subimport{chapters/}{foobar9}'
\subimport{chapters/}{foobar9-yyy}

$ sed 's#^\(\\subimport{chapters/}{[[:alnum:]_]\+\)}$#\1-yyy}#' <<<'\subimport{chapters/}{spamegg923}'
\subimport{chapters/}{spamegg923-yyy}

这是最终为我工作的版本。

sed -i.bak -E 's#^([[:blank:]]*\\subimport{chapters/}{[[:alnum:]_]+)}$#\1-yyy}#' file.tex
rm -f file.tex.bak

非常感谢@heemayl。 他们的答案写得更好,它只需要进行一些调整即可获得适合我的版本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM