使用sed和regex替换OSX和Linux上的文本 [英] Using sed with regex to replace text on OSX and Linux

查看:83
本文介绍了使用sed和regex替换OSX和Linux上的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用正则表达式将文件内的某些字符串替换为sed.使问题复杂化的是,这是在需要同时在osxlinux上运行的Makefile脚本中完成的.

I am trying to replace some strings inside a file with sed using Regular Expressions. To complicate the matter, this is being done inside a Makefile script that needs to work on both osx and linux.

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

Specifically, within file.tex I want to replace

\subimport{chapters/}{xxx}

使用

\subimport{chapters/}{xxx-yyy}

(xxxyyy只是示例文本.)

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

Note, xxx could contain any letters, numbers, and _ (underscore) but really the regex can simply match anything inside the brackets. Sometimes there is some whitespace at the beginning of the line before \subimport....

要搜索的字符串的设计需要大量转义(当使用正则表达式搜索时),我想我的错误就在其中.

The design of the string being searched for requires a lot of escaping (when searched for with regex) and I am guessing somewhere therein lies my error.

这是我到目前为止尝试过的:

Here's what I've tried so far:

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).

This results in an error of RE error: invalid repetition count(s) when I build my Makefile that contains this script.

我认为部分问题是sed-E选项在sedosx版本中不可用.事实证明,使用-E选项时,应转义的东西更少(请参阅我的问题的评论).

I thought part of my problem was that the -E option for sed was not available in the osx version of sed. It turns out, when using the -E option, fewer things should be escaped (see comments on my question).

推荐答案

以下是最终为我工作的版本.

Here's is the version that ended up working for me.

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

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

Much thanks go to @heemayl. Their answer is the better written one, it simply required some tweaking to get a version that worked for me.

这篇关于使用sed和regex替换OSX和Linux上的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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