简体   繁体   English

使用sed替换字符串

[英]string replace using sed

I have a string as below. 我有一个字符串如下。 Using sed i want to replace value detail after name: "user" and also password with "66666" Input String: 使用sed我想在名称:“ user”和密码后用“ 66666”输入字符串替换值详细信息:输入字符串:

        name: "user"
        value: "55555"
        username: "test"
        value: "77777"
        password : "55555"

Expected output: 预期产量:

        name: "user"
        value: "66666"
        username: "test"
        value: "77777"
        password : "66666"

I tried the below but didn't work. 我尝试了以下内容,但没有成功。 It's only replacing password but not value after name 它仅替换密码,而不是名称后的值

sed -i -e 's/\(password\|name: "[^"]*"{\n}value\): "[^"]*"/\1: "66666"/' test.txt

Try this: 尝试这个:

sed -e '/name: *"user"/{' -e ':a;' -e 'N;/password *:/!ba;' -e 's/\(value *: *\)"[^"]*/\1"66666/;s/\(password *: *\)"[^"]*/\1"66666/;}' test.txt
        name: "user"
        value: "66666"
        username: "test"
        value: "77777"
        password : "66666"

sed is a stream editor, by default it reads and dealing with each line separately. sed是一个流编辑器,默认情况下它会读取并分别处理每一行。
Here I used N to read and append the next line, and replace the content in it. 在这里,我使用N读取并追加了下一行,并替换了其中的内容。
I removed -i switch so you can test it on shell first, you can add it back when the results seems ok. 我删除了-i switch,因此您可以先在shell上对其进行测试,然后在结果看起来还可以的时候将其添加回去。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM