Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

How could I replace column 1 in File1 with column 2 in File2, when a match is found?

File1
id1 36987
id2 75685
id3 12345
id4 12896

File2
id1 ID1
id2 ID2
id3 ID3
id5 ID5

I'd like to write this on another File3, that should look like:

File3
ID1 36987
ID2 75685
ID3 12345
id4 12896

I'm currently (unsuccessfully) trying:

sed `File2.txt | awk '{print "-e s/"$1"/"$2"}'`<<< "File1.txt" 
share|improve this question

2 Answers 2

up vote 2 down vote accepted

With awk

$ awk 'NR==FNR {a[$1]=$2; next}; a[$1] {$1=a[$1]} 1' File2 File1
ID1 36987
ID2 75685
ID3 12345
id4 12896
share|improve this answer

I'd use sed to generate the sed script:

sed 's=^=s/=;s= =/=;s=$=/=' File2 | sed -f- File1
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.