LabHub

블로그

Linux grep 명령어 기초

한국어English日本語

Overview

Linux 에는 grep 이라는 유용한 도구가 있습니다. 이 도구를 잘 활용하면, 텍스트 파일에서 유용한 정보를 추출할 수 있습니다.

grep document

grep
$ grep -h
usage: grep [-abcdDEFGHhIiJLlMmnOopqRSsUVvwXxZz] [-A num] [-B num] [-C[num]]
	[-e pattern] [-f file] [--binary-files=value] [--color=when]
	[--context[=num]] [--directories=action] [--label] [--line-buffered]
	[--null] [pattern] [file ...]

options

examples

아래와 같은 test.txt 파일이 있다고 가정하겠습니다.

test.txt
$ cat test.txt

apple is sweety
banana is long
apple mango
pitch is
water melon is expensive
grapes are cheep
pear

grep pattern -A num text

$ grep apple -A 2 test.txt
apple is sweety
banana is long
apple mango
pitch is
water melon is expensive

grep pattern -B num text

$ grep apple -B 1 test.txt
apple is sweety
banana is long
apple mango

grep pattern -C num text

$ grep apple -C 1 test.txt
apple is sweety
banana is long
apple mango
pitch is

grep pattern -c text

grep apple -c  test.txt
2

grep -e pattern text

$ grep -e "ap" test.txt
apple is sweety
apple mango
grapes are cheep

grep -f file text

$ cat regex.txt
apple

$ grep -f regex.txt test.txt
apple is sweety
apple mango

grep -n pattern text

$ grep -n appl test.txt
1:apple is sweety
3:apple mango

grep -v pattern word

appl 을 제외한 줄을 출력.

$ grep -v appl test.txt
banana is long
pitch is
water melon is expensive
grapes are cheep
pear

다른 명령어와 조합

with > (redirection)

grep 결과를 out에 저장

$ grep -v appl test.txt > out.txt
$ cat out.txt
banana is long
pitch is
water melon is expensive
grapes are cheep
pear

with awk

첫 번째 단어만 출력

$ grep -v appl test.txt | awk '{print $1}'
banana
pitch
water
grapes
pear

with sort, uniq

첫번 째 단어를 정렬하고 중복 제거

$ grep ap test.txt | awk '{print $1}' | sort | uniq
apple
grapes

regex에 대해서 더 공부하고 싶거나 test 하고 싶다면, regexr.com에서 공부.

regexr-example

댓글

아직 댓글이 없습니다.

로그인하면 댓글을 쓸 수 있습니다