awkselfish
awkselfish

Reputation: 21

How do I print certain outputs within awk command

file1

[email protected]
[email protected]
[email protected]

file2

[email protected]:200
[email protected]:100
[email protected]:0
[email protected]:201
[email protected]:10

file3 should look like:

[email protected]:200
[email protected]:201
[email protected]:10

I tried:

awk -F, 'BEGIN{OFS=":"} NR==FNR{a[$1$2]=$3;next}'

Upvotes: 1

Views: 42

Answers (1)

Sundeep
Sundeep

Reputation: 23667

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.

Upvotes: 2

Related Questions