Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I want to subtract a constant number from my data to get new data file. For example, I want to subtract 10 from my data.

data.txt

Id  a   b   c   d   e
1   1   2   3   4   5
2   2   3   4   5   6
3   3   4   5   6   7
4   4   5   6   7   8
5   5   6   7   8   9
6   6   7   8   9   10
7   7   8   9   10  11
8   8   9   10  11  12
9   9   10  11  12  13
10  10  11  12  13  14
11  11  12  13  14  15
12  12  13  14  15  16
13  13  14  15  16  17
14  14  15  16  17  18

Required output:

out.txt

Id  a   b   c   d   e
1   -9  -8  -7  -6  -5
2   -8  -7  -6  -5  -4
3   -7  -6  -5  -4  -3
4   -6  -5  -4  -3  -2
5   -5  -4  -3  -2  -1
6   -4  -3  -2  -1  0
7   -3  -2  -1  0   1
8   -2  -1  0   1   2
9   -1  0   1   2   3
10  0   1   2   3   4
11  1   2   3   4   5
12  2   3   4   5   6
13  3   4   5   6   7
14  4   5   6   7   8
share|improve this question

1 Answer 1

up vote 3 down vote accepted

This is trivial in awk:

$ awk '{if(NR>1){for(i=2;i<=NF;i++){$(i)=$(i)-10;}}print;}' data.txt 
Id  a   b   c   d   e
1 -9 -8 -7 -6 -5
2 -8 -7 -6 -5 -4
3 -7 -6 -5 -4 -3
4 -6 -5 -4 -3 -2
5 -5 -4 -3 -2 -1
6 -4 -3 -2 -1 0
7 -3 -2 -1 0 1
8 -2 -1 0 1 2
9 -1 0 1 2 3
10 0 1 2 3 4
11 1 2 3 4 5
12 2 3 4 5 6
13 3 4 5 6 7
14 4 5 6 7 8

To preserve the column alignment, you could pipe through column:

$ awk '{if(NR>1){for(i=2;i<=NF;i++){$(i)=$(i)-10;}}print;}' data.txt | 
     column -t
Id  a   b   c   d   e
1   -9  -8  -7  -6  -5
2   -8  -7  -6  -5  -4
3   -7  -6  -5  -4  -3
4   -6  -5  -4  -3  -2
5   -5  -4  -3  -2  -1
6   -4  -3  -2  -1  0
7   -3  -2  -1  0   1
8   -2  -1  0   1   2
9   -1  0   1   2   3
10  0   1   2   3   4
11  1   2   3   4   5
12  2   3   4   5   6
13  3   4   5   6   7
14  4   5   6   7   8
share|improve this answer
    
How about the Id column? Also it would be nicer with a better aligned output! ;-) –  coffeMug Jan 3 at 12:38
    
@coffeMug ah, good point, fixed. –  terdon Jan 3 at 12:44
    
To column-align the output, pipe into column -t –  glenn jackman Jan 3 at 13:40
    
@glennjackman good point, thanks. –  terdon Jan 3 at 14:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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