Need to edit a line from particular section inside a file using sed in linux

116 views Asked by At

I need to edit the provider line from [token] section in the following file:

$ cat test.txt
[test]

    #provider = keystone.token.providers.uuid.Provider
    #driver = keystone.token.persistence.backends.sql.Token
    #caching = true
    #cache_time = <None>

[token]

    #provider = keystone.token.providers.uuid.Provider
    #driver = keystone.token.persistence.backends.sql.Token
    #caching = true
    #cache_time = <None>

[trust]

    #provider = keystone.token.providers.uuid.Provider
    #driver = keystone.token.persistence.backends.sql.Token
    #caching = true
    #cache_time = <None>

I tried:

sed -e '/^\[token\]/s/^\#provider.*/provider = keystone.token.providers.uuid.Provider/' test.txt

but there were no changes made to the file.

How can I change my script to edit the right section?

2

There are 2 answers

0
Tom Fenech On

Here's how you could do it using awk:

$ awk -v RS= '/\[token]/ {f=1} f && gsub(/#provider/, "provider") {f=0}1' ORS='\n\n' file
[test]

    #provider = keystone.token.providers.uuid.Provider
    #driver = keystone.token.persistence.backends.sql.Token
    #caching = true
    #cache_time = <None>

[token]

    provider = keystone.token.providers.uuid.Provider
    #driver = keystone.token.persistence.backends.sql.Token
    #caching = true
    #cache_time = <None>

[trust]

    #provider = keystone.token.providers.uuid.Provider
    #driver = keystone.token.persistence.backends.sql.Token
    #caching = true
    #cache_time = <None>

Unsetting the record separator RS means that awk reads in each block one at a time. When [token] matches, the flag f is set. When f is set and the substitution is successful, f is unset, so no other substitutions are made. The 1 at the end is a commonly used shorthand which means that each line is printed. The ORS is the output record separator, which is set to two newline characters so you don't lose the space between each block.

0
josifoski On

Even awk is better and clearer for understanding, however in sed

sed -i.bak '/\[token\]/,+2 s/#//' test.txt

with ,+2 you add +2 lines in range