4

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
11

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!)
| improve this answer | |
2

Another awk approachs, including the matched line.

awk '/pattern/, 0' infile

Excluding the matched line.

awk '/pattern/&& getline, 0' infile
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.