将正则正面的正面视角转换为SED操作
我想用-
_ 来查找并替换每一个出现-
,但仅在每行首次出现=
之前。
这是一个可以使用的数据集:
ke-y_0-1="foo"
key_two="bar"
key_03-three="baz-jazz-mazz"
key-="rax_foo"
key-05-five="craz-"
最后,数据集应该看起来像这样:
ke_y_0_1="foo"
key_two="bar"
key_03_three="baz-jazz-mazz"
key_="rax_foo"
key_05_five="craz-"
我发现此正则是正确匹配的。
\-(?=.*=)
但是,正则是正面的lookaheads,看来sed
(即使使用-e
,-e
或-r
)剂量不知道如何与积极的lookaheads一起工作。
我尝试了以下操作,但是在正则表达式之前保持无效
cat dataset.txt | sed -r "s/-(?=.*=)/_/g"
是否有可能用SED可用的方式转换它?
请注意,我不想使用Perl。但是我愿意尴尬。
I would like to sed to find and replace every occurrence of -
with _
but only before the first occurrence of =
on every line.
Here is a dataset to work with:
ke-y_0-1="foo"
key_two="bar"
key_03-three="baz-jazz-mazz"
key-="rax_foo"
key-05-five="craz-"
In the end the dataset should look like this:
ke_y_0_1="foo"
key_two="bar"
key_03_three="baz-jazz-mazz"
key_="rax_foo"
key_05_five="craz-"
I found this regex will match properly.
\-(?=.*=)
However the regex uses positive lookaheads and it appears that sed
(even with -E
, -e
or -r
) dose not know how to work with positive lookaheads.
I tried the following but keep getting Invalid preceding regular expression
cat dataset.txt | sed -r "s/-(?=.*=)/_/g"
Is it possible to convert this in a usable way with sed?
Note, I do not want to use perl. However I am open to awk.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
在线演示:
output:output:
详细信息:
:a a:a a:a a:a a:a
- 设置名为的标签
s/^\([^=]*\) - /\ 1 _/
- 查找以外的任何零或更多chars A=
字符串开头的字符(当捕获到第1组(\ 1
)),然后匹配-
char,并替换为组1值(\ 1
)和A_
(替换找到的-
char)ta
- 跳到成功更换后,LableA
位置。否则,停下来。You can use
See the online demo:
Output:
Details:
:a
- setting a label nameda
s/^\([^=]*\)-/\1_/
- find any zero or more chars other than a=
char from the start of string (while capturing into Group 1 (\1
)) and then matches a-
char, and replaces with Group 1 value (\1
) and a_
(that replaces the found-
char)ta
- jump to lablea
location upon successful replacement. Else, stop.您还可以使用
awk
将字段分隔符设置为=
,然后用-
替换为第一个字段的_
。仅打印替换行:
输出:输出:
如果要打印所有行,
You might also use
awk
setting the field separator to=
and replace all-
with_
for the first field.To print only the replaced lines:
Output
If you want to print all lines: