Ubuntu – How to delete lines from a file until a specific pattern

command linetext processing

I need to look up the line number of a specific match in a file – email address – and then delete it from the beginning of the file until the matched line.

e.g Let's say the line number is 13807. So I need to keep the 13808+ lines intact.

Here's an example:

$ cat input
some
lines
before
mail@server.com
and
some
more
afterwards

$ cat output
and
some
more
afterwards

Best Answer

sed

sed '1,/mail@server\.com/d'  # excluding the matched line
sed '/mail@server\.com/,$!d' # including the matched line

Explanations

  • 1,/mail@server\.com/ddelete every line from line 1 to (,) mail@server.com
  • /mail@server\.com/,$!d – don't (!) delete every line from mail@server.com to (,) the end of the file ($), but everything else

Usage

sed '…' file > file2 # save output in file2
sed -i.bak '…' file  # alter file in-place saving a backup as file.bak
sed -i '…' file      # alter file in-place without backup (caution!)

awk

awk 'f;/mail@server\.com/{f=1}' # excluding the matched line
awk '/mail@server\.com/{f=1}f'  # including the matched line

Explanations

  • f – variable f, variables are 0 = false by default, awk prints nothing if the expression is false and just prints the line if the expression is true
  • /mail@server\.com/{f=1} – if mail@server.com is found set f=1, therefore rendering the whole expression true the next time f occurs in the expression

Usage

awk '…' file > file2                          # save output in file2
awk -iinplace -vINPLACE_SUFFIX=.bak '…' file  # alter file in-place saving a backup as file.bak
awk -iinplace '…' file                        # alter file in-place without backup (caution!)