Search code examples
sedspacing

sed command for postgresql pg_hba.conf modification


I want to edit content of pg_hba.conf using sed :

# "local" is for Unix domain socket connections only
local   all             all                                     peer

to

# "local" is for Unix domain socket connections only
local   all             all                                     trust

For know, I use this command that works:

sed -i 's/local   all             all                                     peer/local   all             all                                     trust/' pg_hba.conf

But I'm looking for a way to bypass all theses spaces


Solution

  • You can use

    sed -E -i 's/local([[:space:]]+)all([[:space:]]+)all([[:space:]]+)peer/local\1all\2all\3trust/' test.conf
    

    Or, since it seems like you have a GNU sed:

    sed -E -i 's/local(\s+)all(\s+)all(\s+)peer/local\1all\2all\3trust/' test.conf
    

    And certainly you can do as potong did in the comments and reduce this to

    sed -E -i 's/(local\s+all\s+all\s+)peer/\1trust/' test.conf
    

    Note:

    • -E enables the POSIX ERE syntax (no need to escape + and (...))
    • ([[:space:]]+) / (\s+) defines capturing groups with IDs starting with 1 that match one or more whitespaces
    • \1, \2 and \3 are placeholders, backreferences to the appropriate group values.

    In s/(local\s+all\s+all\s+)peer/\1trust/, you capture the whole part before peer and match peer, then the whole match is replaced with the part before peer (with \1) + trust.