如何使用 sed 替换一行中的第三个单词
这是我学习 sed 过程中的第三篇文章。我有一个假设的要求。我希望能够用“was”替换每行中的第三个单词,其中单词由空格分隔。
bash$ cat words
hi this is me here
hi this is me again
hi this is me yet again
hi this is me
期望的输出:
hi this was me here
hi this was me again
hi this was me yet again
hi this was me
请大家帮忙了解一下如何使用 sed 来实现这一点。我尝试了一些执行指令,但没有成功。 谢谢,
贾格拉蒂
,我找到了!我找到了!
好吧,我终于得到了正确的指示。这有效:
sed -e 's/[^ ]*[^ ]/was/3' words
This is my 3rd post in the process of learning sed. I have a hypothetical requirement. I want to be able to replace 3rd word in each line by 'was', where words are delimited by space(s).
bash$ cat words
hi this is me here
hi this is me again
hi this is me yet again
hi this is me
Desired output:
hi this was me here
hi this was me again
hi this was me yet again
hi this was me
Could people please help with how to do it with sed. I tried a few executing instructions, but didn't work.
Thanks,
Jagrati
I found it! I found it!
Okay, I got the right instruction at last. This works:
sed -e 's/[^ ]*[^ ]/was/3' words
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您不关心格式,这是一种更简单的方法
if you do not care about formatting, this is a simpler approach
我总是这样做:使用组匹配第一个和第二个单词,然后使用反向引用将它们替换为自身。
I always do it like this: match the first and second word using groups, and then replace them with themselves using a backreference.
这会考虑单词边界而不仅仅是空格,因此当有标点符号时它也有效。它需要 GNU
sed
:This looks at word boundaries rather than only whitespace so it works when there is punctuation, too. It requires GNU
sed
:在任何类型的 sed 中:
In any type of sed: