2

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.

2
  • And you really can't use something better than bash for this? May 16, 2011 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, 2011 at 16:12

1 Answer 1

3

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)
}
2
  • 1
    ... and for cleanliness run the results through sort -n
    – Chris Nava
    May 16, 2011 at 16:47
  • 1
    I like this solution. Is there any easy way to remove duplicates after that?
    – Alp
    May 16, 2011 at 17:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .