awk '{i++;a[i]=$1;b[i]=$2;next}
END{
for(i=1;i in a;i++)
{
f=1;
while (f==1)
{
f=0;
for(j=i+1;j in a;j++)
{
if(b[i]==a[j])
{
b[i]=b[j];
f=1;
}
}
}
}
for(i=1;i in a;i++)
{
print a[i],b[i];
}
}' input.txt
Input:
Output:
Input:
Output:
If you need to get
As output from the second input you can change this line:
if(b[i]==a[j])
to:
if(j!=i&&b[i]==a[j])
and this:
for(j=i+1;j in a;j++)
to:
for(j=1;j in a;j++)
Also note that this code assumes there is not a case where second word of a line is equal to both first word of a line and its second word i.e:
In that case the execution of the code will never ends.