0

I want to change this:

--- BEGINNING OF file.txt ---
# use another authentication method.

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all
--- END ---

... to this:

--- BEGINNING OF file.txt ---
# use another authentication method.

# TYPE  DATABASE        USER            ADDRESS                 METHOD
--- END ---

Here's my latest attempt ("-i" to be added):

sed "s/^\(.*type\s*database\s*user\s*address\s*method\).*$/\1/i" file.txt

Thank you!

wmeitzen
  • 90
  • 11
  • it's not what you search ? -> https://stackoverflow.com/questions/6287755/using-sed-to-delete-all-lines-between-two-matching-patterns – Quentin Geff Jun 29 '17 at 18:11
  • I tried sed '/.*type\s*database\s*user\s*address\s*method\$/!d' pg_hba.conf, though that post's answer was too cryptic for me. Thanks, though. – wmeitzen Jun 29 '17 at 18:23

2 Answers2

5

The s command is, indeed sed's Swiss Army knife, but when you want to delete entire lines, it's the wrong tool. You want the d command:

sed '0,/type\s\+database\s\+user\s\+address\s\+method/I!d'

The address 0,/.../I matches all lines from the beginning of the file (0) to the first line that matches the regular expression, case insensitive (I—available in GNU sed but not POSIX sed). ! inverts the match so d deletes the lines that don't match. Try it online!

Jordan Running
  • 102,619
  • 17
  • 182
  • 182
2

This is also easily done with awk:

$ awk -v f=1 'f 
              {s=tolower($0)}
              s~/type\s+database\s+user\s+address\s+method/{f=!f}' file

Or,

 $ awk 'BEGIN{f=1}
        f 
        {s=tolower($0)}
         s~/type\s+database\s+user\s+address\s+method/{exit}' file

Outline:

 BEGIN{f=1}         # set a flag to true value
 f                  # print if that flag is true
 {s=tolower($0)}    # make the line lowercase
 s~/regex/{exit}    # at the regex but after printing -- exit

Which can be further simplified to:

$ awk '1 
       tolower($0)~/type\s+database\s+user\s+address\s+method/{exit}' file 
dawg
  • 98,345
  • 23
  • 131
  • 206