search and replace exact string

Hello Everyone,

Im trying to run a search and replace of exact strings and the strings that im using variables that are passed through an array in a while loop. Here is a snip of my code:

USEROLD=`cat oldusers`
USERNEW=`cat newusers`
USEROLDARRAY=( $USEROLD )
USERNEWARRAY=( $USERNEW )
arraylength=`cat oldusers | wc -l`
i=0;
while [ "$i" -lt "$arraylength" ]
do
        fromold=${USEROLDARRAY["$i"]};
        fromnew=${USERNEWARRAY["$i"]};
        echo "Replacing $fromold with $fromnew"
        cat groups.almost | sed s/$fromold/$fromnew/g >> tmpfile
        mv tmpfile groups.almost
 
let "i = $i +1"
done
mv groups.almost groups.final

in the oldusers file there is a list of users which some of them have their name in part or other users names so doing a replacment of say the user "lin" with "xlin" has resulted in replacing a user that had the word "lin" in their user name like "maklin" and maklin ends up being "makdlin". I also tried adding \b around my $fromold variable but no such luck. Anyone have an idea? :confused:

try:

sed 's/\b$old\b/$new/g' 

or you can show some your data, I guess using awk can help you to resolve the issue.

no luck. I attached an example of the data but you will have to rename the files since the forums do not except files that dont have extentions or invalid extentions.
Thanks!

try:

awk '
FILENAME=="newusers.txt"{a[FNR]=$0}
FILENAME=="oldusers.txt"{b[$0]=a[FNR]}
FILENAME=="groups.txt"{
             l=split($NF,c,",");$NF="";
             for(i=1;i<=l;i++) $NF=(c in b)?$NF","b[c]:$NF","c;
             sub(",","",$NF);print}
' newusers.txt oldusers.txt FS=':' OFS=':' groups.txt
mygroup1:x:1:dlin,blin,clin
mygroup2:x:2:jbob,jaim,jjohn
mygroup3:x:3:bylin,klin,jlin
1 Like

Perfect! That's exactly what I wanted! Thanks so much!