2
$ cat file1 #It contains ID:Name   
5:John  
4:Michel

$ cat file2 #It contains ID  
5  
4  
3  

I want to Replace the IDs in file2 with Names from file1, output required

John  
Michel  
NO MATCH FOUND  

I need to expand the below code to reult NO MATCH FOUND text.

awk -F":" 'NR==FNR {a[$1]=$2;next} {print a[$1]}' file1 file2 

My current result:

John  
Michel  
        << empty line

Thanks,

3 Answers 3

4

You can use a ternary operator for this: print ($1 in a)?a[$1]:"NO MATCH FOUND". That is, if $1 is in the array, print it; otherwise, print the text "NO MATCH FOUND".

All together:

$ awk -F":" 'NR==FNR {a[$1]=$2;next} {print ($1 in a)?a[$1]:"NO MATCH FOUND"}' f1 f2
John
Michel
NO MATCH FOUND
Sign up to request clarification or add additional context in comments.

1 Comment

you can remove the in check and use print a[$1]?a[$1]:"NO MATCH FOUND" instead.
2

You can test whether the index occurs in the array:

$ awk -F":" 'NR==FNR {a[$1]=$2;next} $1 in a {print a[$1]; next} {print "NOT FOUND"}' file1 file2
John
Michel
NOT FOUND

Comments

0

if file2 has only digit (no space at the end)

awk -F ':' '$1 in A {print A[$1];next}{if($2~/^$/) print "NOT FOUND";else A[$1]=$2}' file1

if not

awk -F '[:[:blank:]]' '$1 in A {print A[$1];next}{if($2~/^$/) print "NOT FOUND";else A[$1]=$2}' file1 file2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.