views:

42

answers:

1

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!

+3  A: 

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 ""
}
schot
schot, many thanks for your detailed codes. It is of great help to me. It seems I must know the length of the blank space.
zhaojing