【发布时间】:2010-09-07 04:18:56
【问题描述】:
我想替换文本的某个字段,同时保留相同的空格:
例如,我的文字是:
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
将解决问题。 但我只是想知道是否有更好的方法? 非常感谢您的关注!
【问题讨论】:
-
您需要知道或计算每个字段的宽度,然后如果字段为 15 个字符宽,则使用 printf 格式代码,例如 '%-15s'。您还必须确保删除所有剩余的旧字段。这篇评论假设 awk 比 sed 更合适——实际上,在 sed 中完成这项工作会非常困难;足够坚韧,我不会费心去尝试。
-
乔纳森,感谢您的 cmets。我一直认为可能有更简单的方法来解决这个问题。可能没有我想的那么简单。
-
如果您使用 gawk 并且事先知道您的字段宽度,则可以使用
FIELDWIDTHS功能获得一个小小的领先。