Searching Text Files : Egrep
Finding text is one of the simplest uses of regular expressions-many text editors and word processors allow you to search a document using a regular-expression pattern. Even more simple is the utility egrep. Give egrep a regular expression and some files to search, and it attempts to match the regular expression to each line of each file, displaying only those lines that are suceessfully matched.
% egrep '^(From|Subject): ' mailbox-file
Figure 1-1 : Invoking egrep from the command lineegrep displays the whole line. The key point is the regular-expression searching is not done on a "word" basis-egrep can understand the concept of bytes and lines in a file, but it generally has no idea of English words, sentences paragraphs, ore othe high-level concepts.
Egrep Metacharacters
egrep metachracter는 정규표현식 사용에 굉장한 도움이 될 때가 많다. 이 과에서는 간단한 예제들을 살펴보자. 자세한 예제는 다음과에서 설명하도록 한다.
Start and End of the Line
아마 가장 이해하기 쉬운 metacharacter는 ^(caret)과 $(dollar)일 것이다. 이 두 metacharacter는 각각 시작과 끝을 나타낸다.
^cat과 cat$은 무슨 차이가 있을까?
^cat은 라인이 cat으로 시작하는 라인, cat$은 cat으로 끝나는 라인을 출력하게 된다. 예를 들면 scat으로 끝나는 라인의 경우 egrep ^cat명령으로는 출력되지 않으며 cat$으로 출력할 수 있다.
조금 더 정규표현적인 사고로 접근해보자.
^cat을 - matches a line with cat at the beginning이라고 생각하기 보다는
^cat을 - matches if you have the beginning of a line, followed immediately by c, followed immediately by a, followed immediately by t. 라고 생각해보자.
두 사고방식이 결국 뜻은 같지만 후자의 사고방식이 정규방식을 이해하는데 좀 더 쉬운 접근 방법이 될 것이다.
^cat$, ^$, ^ 은 각각 어떤 의미가 있을까?
Character Classes
Matching any one of several characters
grey와 gray는 모두 회색을 나타내는 단어이다. 회색이라는 단어를 찾을 때 분명 grey와 gray를 같이 찾아야 할 때가 있다. character class라고 불리는 [...]는 이 경우 아주 유용하게 사용할 수 있다. gr[ea]y 는 g, followed by r, followed by an e or and a, all follwed by y라는 뜻으로 해석할 수 있다.
[Ss]mith 의 경우를 생각해보자. 이는 분명 smith, Smith를 출력시켜줄 것이 분명하지만 blacksmith같이 엉뚱한 단어도 출력할 수 있음을 기억해 두자. ( 차차 이를 어떻게 해결할 수 있는지 설명하겠다)
<H[123456]>의 경우 웹프로그래밍에서 아주 유용할 수 있다. <H1>, <H2>, <H3>, ... , <H6>등의 HTML 헤더를 찾을 수 있다.
위의 character class와 같이 character-class metacharacter '-'(dash)또한 사용 가능하다.
<H[1-6]>는 이 예제에서 이상적인 표현이다. [0-9]와 [a-z]는 각각 digits이나 lowercase letters에 가장 보편적으로 쓰인다.
항상 어떤것이 가장 간편하고 효과적인 방법인지 생각하는 습관을 들이자.
간단히 예제들을 살펴보자. 이전 문제들의 해답이 될 것이다.
Negated character classes
[...] 대신 [^...] 를 사용한다면 어떠한 결과도 출력되지 않는다. 예를 들면 [^1-6]은 1부터 6까지와 각각의 숫자와 일치하는 라인을 출력하지 않는다. ^은 start-of-line caret이기도 했지만 문맥에 따라 완전히 다른 뜻을 나타낸다. ^은 anchor outside a class와 inside a character class에서 각각 다른 뜻을 나타내는 것이다.
q는 대부분의 단어에서 u를 동반하는데, 그렇지 않은 경우의 단어를 찾고싶다면
q[^u]를 사용할 수 있다.
% egrep 'q[^u]' word.list
Iraqi
Iraqian
miqra
qasida
Iraqi
Iraqian
miqra
qasida
하지만 word.list 안에는 Qantas와 Iraq라는 단어도 존재했다. 왜 이 라인은 출력되지 못했을까? 이에대해 더 자세히 공부해보자.
Matching Any character - Dot
dot라고 불리는 . 는 "any character"의 약칭이다. 예를 들어 날짜의 여러표현인 09/01/01, 09-01-01, 09.01.01의 경우 날짜를 표현하기 위해 각각 /, -, . 의 기호가 쓰였다. 이를
09[-./]01[-./]01
또는 간단하게
09.01.01
로 대체할 수 있다.
여기서 혼란스러울 수 있는 몇개의 문제를 짚고 넘어가자. 09[-./]01[-./]01 에서의 dot는 metacharacter가 아니다. 왜냐하면 character class 안에서 쓰였기 때문이다. dash, slash 또한 마찬가지이다. 하지만 09.01.01 에서의 dot는 메타케릭터이다. 이는 dash, period, slash 모두를 기대할 수 있기 때문이다. 하지만 여기서 주의할 점은 dot는 character를 불러올 수도 있다는 점이다. 09c01 01 또한 위의 예제들과 함께 출력될 수 있는 것이다.
Alternation
metching any one of several subexpressions
굉장히 유용한 meta character |는 or이라는 뜻을 나타낸다. 이 표현은 여러 표현들을 하나의 표현으로 통합하는데 유용하게 쓰이는데 (Fir | 1)st [Ss]treet 같은 표현이 그 예이다.
gr[ea]y와 gr(a|e)y는 그 차이가 매우 모호하다. concept of alternation를 that of a character class와 헷갈리는 일이 없도록 하자. character class의 경우 오직 single character를 타겟으로 한다.
^From|Subject|Date: 와 ^(From|Subject|Date):는 어떨까? 두 경우 모두 간단한 예제처럼 보이지만 차이는 크다. 전자의 경우 plain alternatives로 ^From or Subject or Date: 의 뜻이 되어버리며 그닥 유용한 표현식은 아니다. leading ^와 trailing $을 모든 alternative에 적용하고싶다면
^(From|Subject|Date): 가 옳은 표현이 될 것이다.
% egrep '^(From|SubjectlDate): ' mailbox
From: elvis@tabloid.org (The King)
Subject: be seein' ya around
Date: Thu, 31 Oct 96 11:04:13
From: The Prez <president@whitehouse.gov>
Date: Tue, 5 Nov 1996 8:36:24
Subject: now, about your vote...
From: elvis@tabloid.org (The King)
Subject: be seein' ya around
Date: Thu, 31 Oct 96 11:04:13
From: The Prez <president@whitehouse.gov>
Date: Tue, 5 Nov 1996 8:36:24
Subject: now, about your vote...
Word Boundaries
egrep offer limited support.
egrep은 앞선 예제에서와 같이 문장에 대한 컨셉을 세밀하게 나타낼 수는 없다.
버젼에 따라 metasequences \<, \>를 사용할 수 있다.
world-based equivalents of ^, $와 유사한 의미를 나타낸다.
\<cat\> 의 의미는 match if we can find a start of word position, follwed immediately by c.a.t, follwed immediately by and end of word position '.' 로
\<cat
\>cat
형태로 응용할 수 있다. backslash와 함께한 <, >는 metacharacter가 아님을 기억하자. backslash와 결합한 equences는 이처럼 특별해진다. 이러한 표현을 metasequences라고 부른다. 버젼에 따라서 지원되지 않을 수도 있으니 유의하자.
Optional Items
color 혹은 colour와 매칭되는 것을 찾으려면?
이 두 단어의 차이는 u가 있느냐 없느냐의 차이일 것이다. metacharacter ?(question)은 optional의 뜻을 가진다. 캐릭터 뒤의 ?은 whose existence isn't actually required의 의미로 성공적으로 매칭된 데이터를 뽑아낸다.
Thus colou?r 는 즉 as " c , then o then l then o then u? then r . " 의 뜻으로 해석될 수 있겠다.
July? (fourth|4(th)?)
Other Quantifiers : Repitition
+ and *
The metacharacter + , means "one or more of the immediately-preceding item," and * means "any number, including none, of the item." Phrased differently, * means "try to match it as many times as possible, but it's okay to settle for nothing if need be." The construct with plus, + , is similar in that it will also try to match as many times as possible, but different in that it will fail if it can't match at least once.
이 세 metacharacter : question, plus, star는 quantifiers라고 불린다.
(얼마나 많이 매칭되는지와 관계가 있기 때문)