我正在尝试使用正则表达式用 sed
替换文件中的一些字符串。使事情复杂化的是,这是在需要在 osx
和 linux
上工作的 Makefile 脚本中完成的。
具体来说,在 file.tex
我想替换
\subimport{chapters/}{xxx}
与
\subimport{chapters/}{xxx-yyy}
(xxx
和 yyy
只是示例文本。)
请注意,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)
。
我认为我的部分问题是 sed
的 -E
选项在 sed 的
。事实证明,当使用 osx
版本中不可用-E
选项时,应该转义的东西更少(请参阅对我的问题的评论)。
最佳答案
POSIX-ly:
sed 's#^\(\\subimport{chapters/}{[[:alnum:]_]\+\)}$#\1-yyy}#'
#
用作sed
的s
(替换)的参数分隔符\(\\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}
关于regex - 使用带有正则表达式的 sed 替换 OSX 和 Linux 上的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41787537/