How to ignore all lines before a match occurs in bash?

Many ways possible. For example: assuming that your input is in list.txt

PATTERN="R2-01.sql"
sed "0,/$PATTERN/d" <list.txt

because, the 0,/pattern/ works only on GNU sed, (e.g. doesn't works on OS X), here is an tampered solution. ;)

PATTERN="R2-01.sql"
(echo "dummy-line-to-the-start" ; cat - ) < list.txt | sed "1,/$PATTERN/d"

This will add one dummy line to the start, so the real pattern must be on line the 1 or higher, so the 1,/pattern/ will works - deleting everything from the line 1 (dummy one) up to the pattern.

Or you can print lines after the pattern and delete the 1st, like:

sed -n '/pattern/,$p' < list.txt | sed '1d'

with awk, e.g.:

awk '/pattern/,0{if (!/pattern/)print}' < list.txt

or, my favorite use the next perl command:

perl -ne 'print unless 1../pattern/' < list.txt

deletes the 1.st line when the pattern is on 1st line...

another solution is reverse-delete-reverse

tail -r < list.txt | sed '/pattern/,$d' | tail -r

if you have the tac command use it instead of tail -r The interesant thing is than the /pattern/,$d' works on the last line but the1,/pattern/d` doesn't on the first.


How to ignore all lines before a match occurs in bash?

The question headline and your example don't quite match up.

Print all lines from "R2-01.sql" in sed:

sed -n '/R2-01.sql/,$p' input_file.txt

Where:

  • -n suppresses printing the pattern space to stdout
  • / starts and ends the pattern to match (regular expression)
  • , separates the start of the range from the end
  • $ addresses the last line in the input
  • p echoes the pattern space in that range to stdout
  • input_file.txt is the input file

Print all lines after "R2-01.sql" in sed:

sed '1,/R2-01.sql/d' input_file.txt
  • 1 addresses the first line of the input
  • , separates the start of the range from the end
  • / starts and ends the pattern to match (regular expression)
  • $ addresses the last line in the input
  • d deletes the pattern space in that range
  • input_file.txt is the input file
  • Everything not deleted is echoed to stdout.

Tags:

Bash