Rows manupulation using AWK or sed

Hi Everyon,

I am stuck in a script.I have a file named file1.txt as given below:
It contains 2 columns-count and filename.

cat file1.txt
count filename
100 A_new.txt
1000 A_full.txt
1100 B_new.txt
2000 B_full.txt
1100 C_new.txt
2000 C_full.txt
...................
..................

I want to subtract first field of row1 and row2 and store a result in a
variable say "diff". Then
I want to subtract first field of row3 and row4 and store a result in the
variable say "diff". Similary...for rows 5 and 6 and soon......

I am using kshell. I know I have to use AWK or sed but dont know how to.
Any help is apreciated.

Regards,
raj

what exactly u want to do? do u want to overwrite the diff variable or want to store it in a file with specific format?

Hi ROHON,

Thanks for quick reply.

I want to see the difference.After echoing diff, we can overwrtie it.

Regards,
raj.

#!/bin/ksh

xargs -n2 < file1.txt | while read line
do
    set `echo $line | awk -F" " '{print $1 $3}'`
    new=$1 ; full=$2
    diff=$((full - new))
    echo "Diff=$diff"
done

Explanation:

xargs -n2 < file1.txt

this will generate following output

100 A_new.txt 1000 A_full.txt
1100 B_new.txt 2000 B_full.txt
1100 C_new.txt 2000 C_full.txt

so I m reading all lines one by one and fetching 1st and 3rd value of a line separated by space. after than just echoing the diff as per your requirement.

1 Like

Try...

 
awk 'NR>1{s=$1;getline;print "Diff =" s-$1}' infile

Hi ROHON,

Thanks for the reply.
I was trying ur solution.

It gives me following error.

script.sh[6]: full - new: 0403-009 The specified number is not valid for this command.
xargs: 0402-057 The /usr/bin/echo command was not found or could not be run.

And could u pls describe ur code.I would appreciate that.

Regards,
raj.

You can give a try to the above Awk script i posted!!!:wink:

1 Like

I have edited the my previous post #4.

Dear malcomex999,

Thank for the reply.
Your code is working fine. Thanks for that.
I would apprecaite if you could explain this code.
I am not good in AWK.

 
awk 'NR>1                   #  NR(record number) greater than 1
{s=$1                       # assign first column of current record to s
getline                     # get next line
print "Diff =" s-$1         # print s(previous record) minus $1(current record)
}' infile

hope am clear...:slight_smile:

Thank you so much ROHON for the code help. The explaination was great. I have modified it
as per the requirement and I have just delivered the script.

This forum is amazing , I always got help from some body or other when I needed it the most.

Appreciate ur efforts,
regards,
raj.