2

I have two text files.

My first text file looks like this:

2 3
5 9

The second text file looks like this:

4 2 3
3 6 2
1 5 9

I'm trying to separate lines where the values of columns 2 and 3 in the second file have the same values as those in columns 1 and 2 of the first text file.

I'm trying this script but I'm currently not successful and the output is empty.

set a=`awk '{print $1}' 1.txt` 
set b=`awk '{print $2}' 2.txt`
set cc=1
foreach ii ($a)
awk '($2==$a[$cc] && $3==$b[$cc]) {print$0}' 2.txt >> output.txt
@ cc++
end

Can someone help me with this?

1
  • row 1 and 3 of second file Commented Jul 30, 2014 at 14:04

2 Answers 2

1
awk '{ sub(/\r/, ""); } NR == FNR { a[$1 FS $2]++; next } $2 FS $3 in a' file1 file2

Output:

4 2 3
1 5 9
Sign up to request clarification or add additional context in comments.

3 Comments

Why do you think you need to remove \rs? +1 anyway for the right approach and I'm deleting my answer as it's almost identical.
@EdMorton Text editor shows CRLF when I copied it. Just want to make sure it works whatever the format is.
OK. FWIW I don't see that when I copy/paste. Maybe mention it as an option? By the way, You don't need the ++ on the array population and Im surprised you don't need parens around $2 FS $3.
0

You can use grep -f:

grep -f 1.txt 2.txt
4 2 3
1 5 9

Edit: If you want to match only $2 and $3 in 2.txt then use this awk command:

awk 'FNR==NR {a[$1]=$2;next} a[$2]==$3' 1.txt 2.txt
4 2 3
1 5 9

4 Comments

@user3891747 why are you switching between the answers?
@AvinashRaj It's the OP's right to choose the answer that works for him.
yes, you are correct. At first he selected anubhava's then your's now again he selected anubhava's.
This will only co-incidentally produce the expected output from THAT SPECIFIC posted sample input, though, it doesn't provide a solution to the stated problem of matching the values from 1.txt against fields 2 and 3 of 2.txt. Try it if the sample input 2.txt contained a line like 2 3 1 or 1 52 35 or ....

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.