壳:如何替代文本的字段,同时保持相同的空白空间 [英] Shell:How to substitute the field of the text while keeping the same blank space
问题描述
我想替换某日提交的文字,同时保持相同的空白空间:
I want to substitute a certain filed of the text while keeping the same blank space:
例如,我的文字是:
Please help me with this problem
Any suggestion or help will be appreciated
Thanks to all who give help
和我想要替换句子
任何建议或帮助将AP preciated
同
我要解
And I want to replace the sentence "Any suggestion or help will be appreciated" with "I want the solution"
这样的文字是:
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
我将获得
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)的空白空间不与其他人相同的
(1) the blank space is not the same with others.
(2)$ 5,$ 6,$ 7将AP preciated 前行仍然保留。
(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!
推荐答案
下面是 AWK
的例子。这code使用的printf
乔纳森的建议,其宽度说明符。 匹配
是用来寻找正确的宽度。
Here is an example in awk
. This code uses Jonathan's suggestion of printf
with a width specifier. match
is used to find the correct width.
#!/usr/bin/awk -f
BEGIN {
n1 = split("Any suggestion or help will be appreciated", a1)
split("I want the solution", a2)
}
{
j = k = 0
if (NF != n1)
k = 1
for (i = 1; k == 0 && i <= NF; i++)
if ($i != a1[i])
k = 1
if (k) {
print
next
}
for (i = 1; i <= NF; i++) {
match(substr($0, j), /[^ ]+ */)
printf "%-*s", RLENGTH, a2[i]
j += RLENGTH
}
print ""
}
这篇关于壳:如何替代文本的字段,同时保持相同的空白空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!