Shell:如何替换文本的字段,同时保持相同的空格
我想替换文本的某个字段,同时保留相同的空格:
例如,我的文本是:
Please help me with this problem
Any suggestion or help will be appreciated
Thanks to all who give help
我想替换句子 “任何建议或帮助将不胜感激” 和 “我想要解决方案”
这样文本就会是:
Please help me with this problem
I want the solution
Thanks to all who give help
我有一个解决方案:
awk '{if($1=="Any" && $2=="suggestion" && $3=="or" && $4=="help" {$1="I";$2="want";$3="the";$4="solution"};print $0}' eg.txt
我会得到
Please help me with this problem
I want the solution will be appreciated
Thanks to all who give help
正如你所看到的,它有两个问题
(1)空格与其他的不一样。
(2)原行$5、$6、$7“将升值”仍保留。
我知道另一个解决方案:
awk '{if($1=="Any" && $2=="suggestion" && $3=="or" && $4=="help" print "I want the solution";print $0}' eg.txt
将解决问题。 但我只是想知道是否有更好的方法? 非常感谢您的关注!
I want to substitute a certain filed of the text while keeping the same blank space:
For example, my text is:
Please help me with this problem
Any suggestion or help will be appreciated
Thanks to all who give help
And I want to replace the sentence
"Any suggestion or help will be appreciated"
with
"I want the solution"
So that the text will be:
Please help me with this problem
I want the solution
Thanks to all who give help
I have a solution:
awk '{if($1=="Any" && $2=="suggestion" && $3=="or" && $4=="help" {$1="I";$2="want";$3="the";$4="solution"};print $0}' eg.txt
I will get
Please help me with this problem
I want the solution will be appreciated
Thanks to all who give help
As you can see, it has two problems
(1) the blank space is not the same with others.
(2) $5, $6,$7 "will be appreciated" of the former line are still kept.
I know another solution:
awk '{if($1=="Any" && $2=="suggestion" && $3=="or" && $4=="help" print "I want the solution";print $0}' eg.txt
will solve the problem.
But I just wondering if there is better way?
Thanks a lot for your attention!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是 awk 中的示例。此代码使用 Jonathan 建议的带有宽度说明符的
printf
。match
用于查找正确的宽度。Here is an example in
awk
. This code uses Jonathan's suggestion ofprintf
with a width specifier.match
is used to find the correct width.