# Difference operator

**URL:** <https://community.unix.com/t/difference-operator/255153>\
**Category:** Shell Programming and Scripting\
**Created:** [December 4, 2009, 9:00am UTC](https://community.unix.com/t/difference-operator/255153 "2009-12-04T09:00:31Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Fredrick](https://community.unix.com/letter_avatar/fredrick/32/5_5575768a8748004e209b776fc1b2916d.png) [@Fredrick](https://community.unix.com/u/Fredrick)\
**Post date:** [December 4, 2009, 9:00am UTC](https://community.unix.com/t/difference-operator/255153/1 "2009-12-04T09:00:31Z")

</div>

Dear All,

Good day, Just i would like to know that is there anything called difference operator in awk?

For example, if a file contains 5 columns (as shown below) with both negative and positive values:  
Col1 Col2 Col3 Col4 Col5

I need to calculate the difference between Col1 and Col2, Col2 and Col3, Col3 and Col4, Col4 and Col5, and i need to print out the same in an output file as: New\_Col1 New\_Col2 New\_Col3 New\_Col4

Can any one help me in this regard?

Expecting your reply and thanks in advance.

Regards  
Fredrick.

---

<div class="post-metadata">

**Author:** ![Franklin52](https://community.unix.com/user_avatar/community.unix.com/franklin52/32/500_2.png) [@Franklin52](https://community.unix.com/u/Franklin52)\
**Post date:** [December 4, 2009, 9:16am UTC](https://community.unix.com/t/difference-operator/255153/2 "2009-12-04T09:16:34Z")

</div>

Try this, it substracts field 1 with field 2, field 2 with field 3 etc:

```nohighlight
awk '{for(i=1;i<NF;i++){s=s FS $i-$(i+1)}print s;s=""}' file

```

---

<div class="post-metadata">

**Author:** ![ash.g](https://community.unix.com/user_avatar/community.unix.com/ash.g/32/930_2.png) [@ash.g](https://community.unix.com/u/ash.g)\
**Post date:** [December 4, 2009, 9:46am UTC](https://community.unix.com/t/difference-operator/255153/3 "2009-12-04T09:46:22Z")

</div>

What does s=s there signify? Is that like replasing some sting?

---

<div class="post-metadata">

**Author:** ![Franklin52](https://community.unix.com/user_avatar/community.unix.com/franklin52/32/500_2.png) [@Franklin52](https://community.unix.com/u/Franklin52)\
**Post date:** [December 4, 2009, 10:17am UTC](https://community.unix.com/t/difference-operator/255153/4 "2009-12-04T10:17:34Z")

</div>

> [@ash.g](#):
>
> What does s=s there signify? Is that like replasing some sting?

```plaintext
s=s FS $i-$(i+1)

```

This replaces the variable s with itself and adds a field separator FS and the substraction of the 2 fields after s.
