0

So I have file with 3 columns:

9 1 2
2 2 1
5 3 1
7 3 1
5 3 1
2 3 1
8   2 1
3 2 1
1 1 1

I want to remove from the first column particular values and the relative rows, for example 2 and 5 (that are present more times in the same column) and decrement all the values in the first column that are greater than that value. So if I remove first the number 2 I want to obtain:

8 1 2

4 3 1
6 3 1
4 3 1

7 2 1
2 2 1
1 1 1

and then 5(that now is 4) my output would be:

7 1 2


5 3 1


6 2 1
2 2 1
1 1 1

How can I do that? Consider that I have to remove lot of values in the real case and the file is really big.

  • I'm not sure I understand what you mean. How do you decide which rows to remove and why? Can you expand your explanation a little more? – SomeGuy May 7 '18 at 19:05
  • So the file with the 3 columns is a sparse matrix and the first column are coordinates. I have to remove around 60 values that correspond to particular coordinates of the first column but I want also to remove the corresponding rows and keep the remaining coordinates. If the remaining coordinates are greater than the value (2 as the example) I want to reduce that coordinates value of the first column of 1. – shiva May 7 '18 at 19:17
  • @shiva, is it mandatory to retain empty lines? – RomanPerekhrest May 7 '18 at 19:18
  • No I don't want empty lines. I add them only for clarity of the example. – shiva May 7 '18 at 19:20
  • 1
    How are the lines chosen as to which are deleted? – SomeGuy May 7 '18 at 19:36
0

bash + awk solution:

i=0;
for n in 2 5; do
    awk -v n="$n" -v iter=$((++i)) \
   'iter == 1{ 
        if ($1 > n) { $1-- } else if ($1 == n) { next }
    }
    iter > 1{
        if ($1 + 1 == n){ next } else if ($1 >= n) $1-- 
    }1' inp_file > tmp_inpfile && mv tmp_inpfile inp_file
done

The final inp_file contents:

7 1 2
5 3 1
6 2 1
2 2 1
1 1 1
  • can you please explain the code? Thank you. – shiva May 8 '18 at 6:57
  • I recommend you to test this approach on different values in different order. And if it fails in some critical cases - I would rather delete this answer. – RomanPerekhrest May 8 '18 at 7:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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