sed 仅当文件每行中第一次出现的字符是前 2 个字符时才替换它们

发布于 2025-01-17 18:44:18 字数 368 浏览 2 评论 0原文

仅在行中的前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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦罢 2025-01-24 18:44:18

您可以在此处使用

sed -i 's/^15 /0 /' file.txt
sed -i 's/^15\([[:space:]]\)/0\1/' file.txt
sed -i 's/^15\(\s\)/0\1/' file.txt

^匹配字符串位置的开始,15匹配15子字符串,然后空间与空间匹配。

第二和第三个解决方案是相同的,而不是文字空间,它们将Whitespace Char捕获到第1组中,并使用\ 1占位符将组值重新放回结果中。

You can use

sed -i 's/^15 /0 /' file.txt
sed -i 's/^15\([[:space:]]\)/0\1/' file.txt
sed -i 's/^15\(\s\)/0\1/' file.txt

Here, the ^ matches the start of string position, 15 matches the 15 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文