如何在Linux shell脚本中搜索用户id并替换名称
例如a = userId
user.txt内容
A1:Alex:Password1
A2:John:Password2
搜索a2用户ID,
echo -n "Enter user id: "
read userID
然后在我输入用户ID后替换John用户名为Alexander,我需要在user.txt中搜索,找到了用户ID 输入替换名称约翰。
人们可以帮忙做到这一点。我尝试了一些执行说明,但没有起作用。 我该如何在Shell Script Linux中进行操作?感谢
您的帮助 我从答案中找到了如何做到的方式。
echo -n "Enter user id: "
read userID
echo -n "Enter user name: "
read userName
sed -i 's/'$userID':\w*/'$userID':'$userName'/g' user.txt
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
添加到您的bash脚本
sed
命令如下,它将在原地更改
user.txt
文件Add to your bash script
sed
command as followIt will change in-place
user.txt
file另一个简单的方法是使用
awk
。您可以将用户ID和替换名称从shell传递到awk
,然后将记录找到第一个字段($ 1
)与用户ID匹配并替换名称(3rd Five <代码> $ 3 )带有新的代码。字符串(或外壳变量)是通过
-v = value
参数进行awk
变量的,其中id> id
andnm
nm 用于将用户ID和名称称为awk
变量。-v ofs =“:”
将awk
输出字段分隔符设置为“:”
,以便使用新名称修改记录后“:”
被替换为分离器。-f:
告诉awk
使用“:”
作为字段分离器将记录(行)分开为字段。最后的1
只是默认操作打印
即可输出记录的速记。示例使用/输出
使用Heredoc提供您可以做的输入:
Another simple method is using
awk
. You can pass the userID and replacement name from the shell toawk
and then locate the record where the first field ($1
) matches the userID and replace the name (3rd field$3
) with the new one.The strings (or shell variables) are made
awk
variables through the-v=value
parameters whereid
andnm
are used to hold the userID and name asawk
variables.-v OFS=":"
sets theawk
Output Field Separator to":"
so that after the records is modified with the new name, the":"
are replaced as separators. The-F:
tellsawk
to use":"
as the Field Separator to separate the record (line) into fields. The1
at the end is just shorthand for the default operationprint
to output the records.Example Use/Output
Using a heredoc to supply your input you can do: