[英]Modify a file using sed
I have a file in this format 我有这种格式的文件
[file1]
username = admin
password = *****
ips = X.X.X.X
port = 8000
[file2]
username = admin
password = *****
ips = X.X.X.X
port = 8000
I want to modify the username and password for both sections in the file using a bash script. 我想使用bash脚本修改文件中两个部分的用户名和密码。
I need the output to be: 我需要的输出是:
[file1]
username = user1
password = user1
ips = X.X.X.X
port = 8000
[file2]
username = user2
password = user2
ips = X.X.X.X
port = 8000
This is the sed
command which I tried: 这是我尝试的sed
命令:
sed 's/username = admin/username = user1/' file [file1] username = user1 password = ***** ips = X.X.X.X port = 8000 [file2] username = user1 password = ***** ips = X.X.X.X port = 8000
I am trying to use a sed command to achieve this but it finds and replaces all usernames and passwords with same value. 我正在尝试使用sed命令来实现此目的,但它会查找并替换具有相同值的所有用户名和密码。 Can anyone help me sort this out? 谁能帮我解决这个问题?
sed 's/username = admin/username = user1/' x
[file1]
username = user1
password = *****
ips = X.X.X.X
port = 8000
[file2]
username = user1
password = *****
ips = X.X.X.X
port = 8000
Appreciate your help in advance! 提前感谢您的帮助!
-W -W
Could you please try following. 您可以尝试以下吗?
Solution 1st: Taking the number from file
string in the line and then adding it to user
and password
string lines. 解决方案1:从行中的file
字符串中获取数字,然后将其添加到user
和password
字符串行中。
awk '/file/{val=$0;gsub(/[a-zA-Z]|+|\[|\]/,"",val)} /^user/||/^password/{$NF="user"val} 1' Input_file
Solution 2nd: In this approach simply having a variable count
which will be incremented by 1
each time it sees file
string on it. 解决方案2nd:在这种方法中,仅具有一个变量count
,每次在其上看到file
字符串时,该count
将增加1
。
awk '/file/{count++} /^user/||/^password/{$NF="user"count} 1' Input_file
In case you want to save output into Input_file itself append > temp_file && mv temp_file Input_file
in above codes too. 如果您想将输出保存到Input_file本身,请在上述代码中附加> temp_file && mv temp_file Input_file
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.