Home > Back-end >  How to search user id and replace name in shell script Linux
How to search user id and replace name in shell script Linux

Time:04-02

For example A = UserID

user.txt content

A1:Alex:Password1
A2:John:Password2

Search A2 User ID and Replace John username as Alexander

echo -n "Enter user id: "
read userID

After i enter the user id, i need to search in user.txt, after found the user id Enter the replace name John.

Could people please help with how to do it. I tried a few executing instructions, but didn't work. How can i do it in Shell Script Linux ? Thanks

Thanks for helping I found the way how to do it from answer.

echo -n "Enter user id: "
read userID
echo -n "Enter user name: "
read userName

sed -i 's/'$userID':\w*/'$userID':'$userName'/g' user.txt

CodePudding user response:

Add to your bash script sed command as follow

#!/bin/bash
echo -n "Enter user id: "
read userID

sed -i 's/A2:\w*:/A2:'$userID':/g' user.txt

It will change in-place user.txt file

CodePudding user response:

Another simple method is using awk. You can pass the userID and replacement name from the shell to awk and then locate the record where the first field ($1) matches the userID and replace the name (3rd field $3) with the new one.

awk -v id="A2" -v nm="Alexander" -v OFS=":" -F: '$1==id {$3=nm}1' user.txt

The strings (or shell variables) are made awk variables through the -v=value parameters where id and nm are used to hold the userID and name as awk variables. -v OFS=":" sets the awk Output Field Separator to ":" so that after the records is modified with the new name, the ":" are replaced as separators. The -F: tells awk to use ":" as the Field Separator to separate the record (line) into fields. The 1 at the end is just shorthand for the default operation print to output the records.

Example Use/Output

Using a heredoc to supply your input you can do:

$ awk -v id="A2" -v nm="Alexander" -v OFS=":" -F: '$1==id {$3=nm}1' << eof
> A1:Alex:Password1
> A2:John:Password2
> eof
A1:Alex:Password1
A2:John:Alexander

  • Related