Shell:如何在保持相同空格的同时替换文本字段

时间:2010-09-07 04:18:56

标签: shell sed awk

我希望在保留相同空格的同时替换文本的某个字段:

例如,我的文字是:

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 

将解决问题。 但我只是想知道是否有更好的方法? 非常感谢您的关注!

1 个答案:

答案 0 :(得分:3)

以下是awk中的示例。此代码使用Jonathan建议的printf和宽度说明符。 match用于查找正确的宽度。

#!/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 ""
}