1

I have a file named testfile.It contains some information like

methun:x:500:500:comment:/home/methun:bin/bash
salahuddin:x:501:500:comment:/home/methun:bin/bash

Now implemented a following shell program:

 echo "Enter a Name:"
   read username
   users='cat /mypractice/myfiles/testfile | awk -F ':' '{print $1}''
   for user in $users
    do
      if [ "$user" == "$username" ]; then
        echo "Name found and Enter a new name to change."
        read newUsername
          #need code to change text on my file --->testfile
      fi
    done

Now suppose I need to change methun to Moin. Comment to newcomment. I used

sed -i 's/"$user"/"$newuser"/g' /mypractice/myfiles/testfile

But it not working here. I test with it in my testfile singly it change and replace all.But i need to change only that position i want .

I also tried with usermod but it will not works here..

Can anyone give me the solution or correct my code...Thanks

1 Answer 1

1

You are using g flag in your sed command which means global substitution (will change all occurrences). Also, the variables although quoted are wrapped inside single quotes and hence are not interpolated.

Try this:

sed -i "s/^$user/$newuser/" /mypractice/myfiles/testfile

I have placed a ^ anchor in the substitution part which means only substitute if the word is at the beginning of the line. This protects you from making a change if the name of the user is not at the start but somewhere in the middle.

Sign up to request clarification or add additional context in comments.

3 Comments

But i want to change only the name that match on the if condition.
@user3464541 Right, just put this sed under your if condition. So if the condition returns true, you can make the change.
suppose i have methun, methun1, methun2, methun3. want to replace methun with jon. When i input methun and want to change name with jon then i found the result like jon jon1 jon2 jon3 But my expected result is like jon methun1 methun2 methun3.

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.