简体   繁体   中英

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:

        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.
Here I used N to read and append the next line, and replace the content in it.
I removed -i switch so you can test it on shell first, you can add it back when the results seems ok.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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