sed 仅当文件每行中第一次出现的字符是前 2 个字符时才替换它们
仅在行中的前2个字符时,才有可能使用SED替换文件线中的第一次出现或substring?
例如,我们有此文本文件:
15 hello
15 h15llo
1 hello
1 h15loo
使用以下命令:sed -i's/s/15/0/'file.txt
将使此输出
0 hello
0 h15llo
1 hello
1 h0loo
我试图避免的是考虑过去的字符过去第2个。 这可能吗?
所需的输出:
0 hello
0 h15llo
1 hello
1 h15loo
Is it possible using sed to replace the first occurrence of a character or substring in line of file only if it is the first 2 characters in the line?
For example we have this text file:
15 hello
15 h15llo
1 hello
1 h15loo
Using the following command: sed -i 's/15/0/' file.txt
Will give this output
0 hello
0 h15llo
1 hello
1 h0loo
What I am trying to avoid is it considering the characters past the first 2.
Is this possible?
Desired output:
0 hello
0 h15llo
1 hello
1 h15loo
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在此处使用
,
^
匹配字符串位置的开始,15匹配15
子字符串,然后空间与空间匹配。第二和第三个解决方案是相同的,而不是文字空间,它们将Whitespace Char捕获到第1组中,并使用
\ 1
占位符将组值重新放回结果中。You can use
Here, the
^
matches the start of string position, 15 matches the15
substring and then a space matches a space.The second and third solutions are the same, instead of a literal space, they capture a whitespace char into Group 1 and the group value is put back into the result using the
\1
placeholder.