替换仅限于每个输入行的一部分的字符 [英] 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
循环的 Sed (BRE):
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屋!