Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I display data from the beginning of a file until the first occurrence of a regular expression?

Tags:

regex

sed

awk

perl

How do I display data from the beginning of a file until the first occurrence of a regular expression?

For example, if I have a file that contains:

One
Two
Three
Bravo
Four 
Five

I want to start displaying the contents of the file starting at line 1 and stopping when I find the string "B*". So the output should look like this:

One
Two
Three
like image 443
Pete Avatar asked Dec 22 '09 13:12

Pete


People also ask

What is regular expression quantifier?

quantifier matches the preceding element one or more times, but as few times as possible. It is the lazy counterpart of the greedy quantifier + . For example, the regular expression \b\w+?\ b matches one or more characters separated by word boundaries.

What does in regular expression mean?

A regular expression (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation.

How does regex replace work?

The REGEXREPLACE( ) function uses a regular expression to find matching patterns in data, and replaces any matching values with a new string. standardizes spacing in character data by replacing one or more spaces between text characters with a single space.

How do you match a character sequence in regex?

Most characters, including all letters ( a-z and A-Z ) and digits ( 0-9 ), match itself. For example, the regex x matches substring "x" ; z matches "z" ; and 9 matches "9" . Non-alphanumeric characters without special meaning in regex also matches itself. For example, = matches "=" ; @ matches "@" .


1 Answers

perl -pe 'last if /^B/' source.txt

An explanation: the -p switch adds a loop around the code, turning it into this:

while ( <> ) {
    last if /^B.*/;  # The bit we provide
    print;
}

The last keyword exits the surrounding loop immediately if the condition holds - in this case, /^B/, which indicates that the line begins with a B.

like image 96
rjh Avatar answered Sep 18 '22 06:09

rjh