Issue
I've ran into a problem! I simply do not have enough knowledge to solve this on my own so if anyone is able to help me that'd be appreciated.
I have two text files: file1.txt
and file2.txt
; they have similar formatting but not exact. Names are on separate line numbers and the files have different line counts. Doing this manually wouldn't be viable due to the amount of data in the files.
Example of file formats:
file1.txt
NAME:FLAT
Jerome:Flat 6
Jimmy:Flat 4
file2.txt
0:NAME:JOB:MONEY:FLAT
1:Bob:Developer:$500:Flat 7
2:Jerome:Gardener:$50:Flat 6
3:Cindy:Graphics:$100:Flat 5
4:Jimmy:Mod:$150:Flat 4
I'm trying to search through file1.txt to see which NAME matches with file2's NAME and print out the full line of file2.txt into a new text document.
Here's an example of what I would like to do:
Checks matching NAME in file1.txt and file2.txt
Ignores "1:Bob:Developer:$500:Flat 7" because Bob only exists in file2.txt
Pastes "2:Jerome:Gardener:$50:Flat 6" into file3.txt because Jerome exists in file1.txt and file2.txt
Ignores "3:Cindy:Graphics:$100:Flat 5" because Cindy only exists in file2.txt
Pastes "4:Jimmy:Mod:$150:Flat 4" into file3.txt because Jimmy exists in file1.txt and file2.txt
How file3 would look File3.txt
2:Jerome:Gardener:$50:Flat 6
4:Jimmy:Mod:$150:Flat 4
Thanks for reading! If anyone could let me know if this is possible that'd be great.
EDIT: What I have so far
awk -F ":" 'FNR==NR{a[$1];next}($1 in a){print}' file2.txt file1.txt > file3.txt
Solution
With your shown samples, could you please try following. Written and tested with GNU awk
.
awk '
BEGIN { FS=":" }
FNR==1 { next }
FNR==NR{
arr[$1]
next
}
($2 in arr)
' file1.txt file2.txt
Explanation: Adding detailed explanation for above.
awk ' ##Starting awk program from here.
BEGIN { FS=":" } ##Starting BEGIN section from here and setting FS as : here.
FNR==1 { next } ##Checking if this is first line in any of Input_file then simply go to next line.
FNR==NR{ ##This condition will be TRUE when file1.txt is being read.
arr[$1] ##Creating array with $1 as key here.
next ##next will skip all further statements from here.
}
($2 in arr) ##Checking condition if 2nd fueld is in arr then print line from file2.txt
' file1.txt file2.txt ##Mentioning Input_file names here.
Answered By - RavinderSingh13 Answer Checked By - Pedro (WPSolving Volunteer)