LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Hello! And also trying to make "matching" script that compares two variables/files (https://www.linuxquestions.org/questions/linux-newbie-8/hello-and-also-trying-to-make-matching-script-that-compares-two-variables-files-4175501996/)

Atterus 04-16-2014 05:37 PM

Hello! And also trying to make "matching" script that compares two variables/files
 
Hello!

I'm relatively new to Linux as a whole and especially this forum :) I use Linux csh scripts primarily in research applications since it is so powerful and flexible. Anyways, I am having trouble getting a csh script to behave where I have two variables (these can be made into files if needed) that comprise of numbers:

file1:
1
2
3
4
5

file2:
1 564
2 2345
8 23
3 6772
4 2
5 1.45
6 24

What I am trying to do is make it so that when the numbers in the first column match up, it prints out the entire line in file2. I've seen lots of threads on simply getting the first column to work, but I can't figure out getting the following kind of result:

res_file:
1 564
2 2345
3 6772
4 2
5 1.45

Removing the file2 lines not corresponding to file1. I've used alot of the suggestions from here in the past, looking forward to actually being in the community! Thanks ahead of time.

schneidz 04-16-2014 06:02 PM

i think you can use awk for this:
Code:

[schneidz@hyper ~]$ head atterus-*
==> atterus-1.txt <==
1
2
3
4
5

==> atterus-2.txt <==
1 564
2 2345
8 23
3 6772
4 2
5 1.45
6 24
[schneidz@hyper ~]$ for num in `cat atterus-1.txt`
do
 awk -v n=$num '$1 == n {print $0}' atterus-2.txt
done
1 564
2 2345
3 6772
4 2
5 1.45


Atterus 04-16-2014 06:30 PM

Thanks! I will try this.

grail 04-16-2014 11:54 PM

awk can actually perform the entire task:
Code:

awk 'NR==FNR{a[$1];next}$1 in a' file1 file2

Atterus 04-17-2014 02:04 PM

@schneidz: Thanks for the answer, unfortunately I don't think that my computer is able to use that particular code. I've seen for loop solutions in the past that my computer doesn't seem to recognize, it just crashed with a bunch of errors and claims it can't do the "for" command. It's frustrating for sure since I'm used to for loops on other programs.

@grail: Worked like a charm! Thanks!

Thanks you two! Very prompt as I would expect from this community!


All times are GMT -5. The time now is 09:24 AM.