awk -F: 'NR==FNR{a[$0]; next} $1 in a' file1 file2
-F:
set :
as field separator
NR==FNR{a[$0]; next}
build array keys based on complete line contents of file1
$1 in a
print line from file2
if first field is a key in array a
Looks like your files may have dos-style line ending, in which case you can use:
awk -F: 'NR==FNR{sub(/\r$/, ""); a[$0]; next} $1 in a' file1 file2
Here, the carriage return at the end of lines in file1
is removed before using it as a key, thus it will match first field of file2
. Also, output will be dos-style.
See also Why does my tool output overwrite itself and how do I fix it?
If there are whitespace characters like space, tab, etc at end of line, that can also cause issue. In such a case, use
awk -F: 'NR==FNR{sub(/[[:space:]]*$/, ""); a[$0]; next} $1 in a' file1 file2
This will remove extra whitespaces at end of line before using it as a key. This will also work for dos-style files.