wmeitzen
wmeitzen

Reputation: 110

How do I delete everything until the end of a file after a pattern using sed?

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!

Upvotes: 0

Views: 2564

Answers (2)

dawg
dawg

Reputation: 103814

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 

Upvotes: 2

Jordan Running
Jordan Running

Reputation: 106027

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!

Upvotes: 5

Related Questions