Sunday, October 24, 2021

[SOLVED] Replacing a specific field using awk, sed or any POSIX tool

Issue

I have a huge file1, which has values as follows:

a 1
b 2
c 3
d 4
e 5

I have another huge file2, which is colon delimited with seven fields as follows:

a:2543:2524:2542:252:536365:54654
c:5454:5454:654:54:87:54
d:87:65:1:98:32:87

I want to search the lines for the variables of file1 and replace its value in the 7th column in file2 so the output should be as follows:

a:2543:2524:2542:252:536365:1
c:5454:5454:654:54:87:3
d:87:65:1:98:32:4

Solution

So I came up with a solution; ended up with a couple of lines of code. Maybe there is a better way to do it.But this works !

while read line ; do 
  var1=`echo $line| awk '{print $1}'`
  var2=`echo $line| awk '{print $2}'`
  awk -v var1="$var1" -v var2="$var2" -F ':' 'BEGIN { OFS = ":"} $1==var1 {sub(".*",var2,$7)}{print}' file2 > file2.tmp
  mv file2.tmp file2
done < file1
cat file2


Answered By - Imran Rentia