I have a textfile with an arbitrary number of rows triplets like these:

4   5   2
12  16  6

Now I want to add related rows to the file. Let's say i want to add 4 additional rows per row which have similar values. The first two columns are slightly altered (-1 and +1 for exactly one of them, all four combinations) and for the third column the value is halved:

4   5   2   (original row)
3   5   1   (added rows)
5   5   1
4   4   1
4   6   1
12  16  6   (original row)
11  16  3   (added rows)
13  16  3
12  15  3
12  17  3

It does not matter where the rows are appended, so it's ok if the added rows are all at the end of the file.

link|improve this question
And you really can't use something better than bash for this? – Ignacio Vazquez-Abrams May 16 '11 at 16:11
Ok i am willing to use Perl, PHP or C++ also. Bash would be most elegant and hopefully with a better performance. What's your suggestion? – Alp May 16 '11 at 16:12
feedback

1 Answer

up vote 2 down vote accepted

awk:

#!/usr/bin/awk -f
BEGIN { OFS = "\t" }
{
    print
    print $1 - 1, $2, $3 / 2
    print $1 + 1, $2, $3 / 2
    print $1, $2 - 1, $3 / 2
    print $1, $2 + 1, $3 / 2
}

This depends a bit on how you need your output formatted, of course. Above example assumes tab separated input records.


To remove duplicates after this, pipe the output through sort -n | uniq.

A variant that doesn't print them in the first place (and so keeps the original order) could store the seen values in an array and only print new ones:

#!/usr/bin/awk -f
function printnew(a, b, c) {
    if(seen[a, b, c] != 1) {
        seen[a, b, c] = 1
        print a, b, c
    }
}

BEGIN { OFS = "\t" }

{
    printnew($1, $2, $3)
    printnew($1 - 1, $2, $3 / 2)
    printnew($1 + 1, $2, $3 / 2)
    printnew($1, $2 - 1, $3 / 2)
    printnew($1, $2 + 1, $3 / 2)
}
link|improve this answer
1  
... and for cleanliness run the results through sort -n – Chris Nava May 16 '11 at 16:47
I like this solution. Is there any easy way to remove duplicates after that? – Alp May 16 '11 at 17:55
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.