限于每个输入行一部分的字符替换 [英] Substitution of characters limited to part of each input line
问题描述
有一个文件,例如. Inventory.conf中包含以下行:
Have a file eg. Inventory.conf with lines like:
Int/domain—home.dir=/etc/int
我需要在=
之前而不是之后替换/
和—
.
结果应该是:
I need to replace /
and —
before the =
but not after.
Result should be:
Int_domain_home_dir=/etc/int
我尝试了几个sed
命令,但似乎都不符合我的需求.
I have tried several sed
commands but none seem to fit my need.
推荐答案
带有t
循环(BRE)的Sed:
Sed with a t
loop (BRE):
$ sed ':a;s/[-/—.]\(.*=\)/_\1/;ta;' <<< "Int/domain—home.dir=/etc/int"
Int_domain_home_dir=/etc/int
当找到-/—.
字符之一时,将其替换为_
.捕获直至=
的后续文本,并使用反向引用输出.如果先前的替换成功,则t
命令循环以标记:a
以检查是否有进一步的替换.
When one of the -/—.
character is found, it's replaced with a _
. Following text up to =
is captured and output using backreference. If the previous substitution succeeds, the t
command loops to label :a
to check for further replacements.
如果您使用的是BSD/Mac OSX(感谢@ mklement0):
If you're under BSD/Mac OSX (thanks @mklement0):
sed -e ':a' -e 's/[-/—.]\(.*=\)/_\1/;ta'
这篇关于限于每个输入行一部分的字符替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!