bash script to find the difference between the 4th element of each line in 2 files
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
bash script to find the difference between the 4th element of each line in 2 files
Hi All,
I have 2 data files. I want a shell script to get the 4th element on each line of each file, and take the difference and store it in a variable. (1st line are junk description, it would be good if u could write code to ignore the 1st 2 line and start reading from the third line)
To read from one file is simple:
while read a
do
echo "$a" | 'awk [print $4]'
done <"filename"
sth like above.
Now, how do I read the other file simultaneously and pull out the 4th element and take the difference.
A quick solution will be very much appreciated.
Thanks much!
#!/usr/bin/perl
use strict;
use warnings;
my $file1 = shift || die "please specify two files as arguments\n";
my $file2 = shift || die "please specify two files as arguments\n";
open(F1, "<$file1") || die "cannot open $file1 : $!\n";
open(F2, "<$file2") || die "cannot open $file2 : $!\n";
while(!eof(F1)&&!eof(F2)) {
my $v1 = (split(/\s+/, <F1>))[3];
my $v2 = (split(/\s+/, <F2>))[3];
printf "%-4d - %-4d == %d\n", $v2, $v1, ($v2 - $v1);
}
close(F1);
close(F2);
The program will terminate when the end of either file is detected. No checking is done to make sure the required values from the input files are actually numerical, so you'll get a warning or two if they are not.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.