Linux에서 텍스트 처리: grep, awk, 그리고 실제로 작업을 수행하는 파이프

발행: (2025년 12월 16일 오전 07:31 GMT+9)
12 min read
원문: Dev.to

Source: Dev.to

번역을 진행하려면 전체 텍스트를 제공해 주시겠어요? 텍스트를 주시면 요청하신 대로 한국어로 번역해 드리겠습니다.

문제: 파일을 수동으로 검색하기

10,000줄짜리 로그 파일에서 모든 오류 메시지를 찾아야 합니다. 혹은 시스템 파일에서 사용자 이름을 추출하거나, 액세스 로그에서 특정 IP 주소가 나타난 횟수를 세어야 할 수도 있습니다.

편집기에서 파일을 열어 수동으로 검색하시나요? 느리고 실수가 발생하기 쉽습니다.

Linux 텍스트 처리 도구를 사용하면 이러한 작업을 한 줄 명령으로 처리할 수 있습니다.

Source:

cut 명령 – 열 추출

cut은 각 행에서 특정 문자 또는 필드를 추출합니다.

문자 위치별

# Get first character from each line
cut -c1 file.txt

# Get characters 1‑3
cut -c1-3 file.txt

# Get characters 1, 2, and 4
cut -c1,2,4 file.txt

실제 예제 – 파일 권한 추출

ls -l | cut -c1-10
# Output: drwxr-xr-x, -rw-r--r--, etc.

Source:

awk 명령 – 패턴 스캔 및 처리

awk는 필드(열)를 추출하고 조작하는 데 강력합니다.

기본 필드 추출

# Print first column
awk '{print $1}' file.txt

# Print first and third columns
awk '{print $1, $3}' file.txt

# Print last column (NF = number of fields)
ls -l | awk '{print $NF}'
# Shows filenames from ls -l output

검색 및 출력

# Find lines containing "Jerry" and print them
awk '/Jerry/ {print}' file.txt

# Or shorter:
awk '/Jerry/' file.txt

필드 구분자 변경

# Use colon as delimiter (common in /etc/passwd)
awk -F: '{print $1}' /etc/passwd
# Output: list of all usernames

필드 수정

# Replace second field with "JJ"
echo "Hello Tom" | awk '{$2="JJ"; print $0}'
# Output: Hello JJ

길이로 필터링

# Get lines longer than 15 characters
awk 'length($0) > 15' file.txt

실전 예시 – IP 주소 추출

# Get IP addresses from access log
awk '{print $1}' /var/log/nginx/access.log

# Count unique IPs
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c

grep 명령 – 텍스트 검색

grep (global regular expression print)는 파일이나 출력에서 키워드를 검색합니다.

기본 검색

# Find keyword in file
grep keyword filename

# Search in output
ls -l | grep Desktop

유용한 옵션

# Count occurrences
grep -c keyword file.txt

# Ignore case
grep -i keyword file.txt
# Finds: keyword, Keyword, KEYWORD

# Show line numbers
grep -n keyword file.txt
# Output: 5:line with keyword

# Exclude lines with keyword (invert match)
grep -v keyword file.txt

실제 예시 – 로그에서 오류 찾기

# Find all error lines
grep -i error /var/log/syslog

# Count errors
grep -i error /var/log/syslog | wc -l

# Find errors but exclude specific ones
grep -i error /var/log/syslog | grep -v "ignore_this_error"

egrep 명령 – 여러 키워드

egrep (또는 grep -E)은 한 번에 여러 패턴을 검색합니다.

# Search for keyword1 OR keyword2
egrep -i "keyword1|keyword2" file.txt

# Find lines with error or warning
egrep -i "error|warning" /var/log/syslog

sort 명령 – 알파벳 순서 정렬

# Sort alphabetically
sort file.txt

# Reverse sort
sort -r file.txt

# Sort by second field
sort -k2 file.txt

실제 예시 – 파일 크기별 정렬

# Sort files by size (5th column in ls -l)
ls -l | sort -k5 -n
# -n flag for numerical sort

uniq 명령 – 중복 제거

uniq는 중복된 라인을 필터링합니다. 중요: 입력은 먼저 정렬되어야 합니다.

# Remove duplicates
sort file.txt | uniq

# Count duplicates
sort file.txt | uniq -c
# Output: 3 line_content (appears 3 times)

# Show only duplicates
sort file.txt | uniq -d

실제 예시 – 가장 흔한 로그 항목

# Find most common errors
grep error /var/log/syslog | sort | uniq -c | sort -rn | head -10

분해 설명

단계목적
grep error오류 라인 찾기
sort동일한 라인들을 그룹화
uniq -c각 라인의 발생 횟수 계산
sort -rn카운트 기준 정렬 (숫자, 내림차순)
head -10상위 10개 결과 표시

wc 명령 – 라인, 단어, 바이트 수 세기

wc (word count)는 파일을 읽고 개수를 보고합니다.

# 라인, 단어, 바이트 수 세기
wc file.txt
# Output: 45 300 2000 file.txt

# 라인만
wc -l file.txt

# 단어만
wc -w file.txt

# 바이트만
wc -c file.txt

실제 예시

# 디렉터리 내 파일 수 세기
ls -l | wc -l

# 키워드가 나타나는 횟수 세기
grep keyword file.txt | wc -l

# 파이썬 파일의 전체 코드 라인 수 세기
find . -name "*.py" -exec wc -l {} \; | awk '{sum+=$1} END {print sum}'

파일 비교 – diff

라인별 비교

# 파일 비교
diff file1.txt file2.txt

# 출력은 차이를 보여줍니다:
#  file2에 있는 라인

Byte‑by‑Byte Comparison – cmp

# 파일 비교
cmp file1.txt file2.txt

# 출력: 차이가 있는 첫 번째 바이트
# 파일이 동일하면 출력 없음

파이프를 사용한 명령 결합

실제 힘은 명령을 연결해서 사용할 때 나옵니다.

예제 1: 찾기 및 개수 세기

# /bin/bash를 쉘로 사용하는 사용자는 몇 명인가요?
grep "/bin/bash" /etc/passwd | wc -l

예제 2: 가장 큰 파일 상위 5개

ls -lh | sort -k5 -h -r | head -5

예제 3: 추출 및 정렬

# 모든 사용자 이름을 가져와 정렬합니다
awk -F: '{print $1}' /etc/passwd | sort

예제 4: 검색, 추출, 개수 세기

# /admin에 접근한 IP 주소 찾기
grep "/admin" /var/log/nginx/access.log \
    | awk '{print $1}' \
    | sort \
    | uniq -c \
    | sort -rn

이것은 /admin에 가장 자주 접근한 IP를 보여줍니다.

예제 5: 로그 분석

# 가장 흔한 오류 유형 찾기
grep -i error /var/log/app.log \
    | awk '{print $5}' \
    | sort \
    | uniq -c \
    | sort -rn \
    | head -10

실제 시나리오

시나리오 1: 큰 파일 찾기

# Files larger than 100 MB
find / -type f -size +100M 2>/dev/null \
    | xargs ls -lh \
    | awk '{print $5, $NF}'

시나리오 2: 활성 연결 모니터링

# Count connections per IP
netstat -an | grep ESTABLISHED \
    | awk '{print $5}' \
    | cut -d: -f1 \
    | sort \
    | uniq -c \
    | sort -rn

시나리오 3: 실패한 로그인 시도 확인

# Count failed SSH attempts by IP
grep "Failed password" /var/log/auth.log \
    | awk '{print $11}' \
    | sort \
    | uniq -c \
    | sort -rn

시나리오 4: 디렉터리별 디스크 사용량

# Top 10 directories by size
du -h /var | sort -h -r | head -10

시나리오 5: 이메일 주소 추출

# Find all email addresses in a file
grep -Eo '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}' file.txt \
    | sort \
    | uniq

Common Patterns

Pattern 1: Search, Extract, Sort, Count

grep pattern file | awk '{print $2}' | sort | uniq -c | sort -rn

Pattern 2: Filter and Process

cat file | grep -v exclude_pattern | awk '{print $1}'

Pattern 3: Multiple Conditions

egrep "error|warning" file | grep -v "ignore" | wc -l

Quick Reference

cut

cut -c1-3 file        # 문자 1‑3
cut -d: -f1 file      # 첫 번째 필드 (구분자 :)

awk

awk '{print $1}' file                # 첫 번째 열
awk -F: '{print $1}' file            # 사용자 정의 구분자
awk '/pattern/ {print}' file        # 패턴 매칭
awk '{print $NF}' file               # 마지막 열
awk 'length($0) > 15' file           # 15자 초과 라인

grep

grep pattern file                   # 검색
grep -i pattern file                # 대소문자 무시
grep -c pattern file                # 일치 횟수
grep -n pattern file                # 라인 번호 표시
grep -v pattern file                # 반전 (제외)
egrep "pat1|pat2" file              # 여러 패턴

sort

sort file                           # 알파벳 순
sort -r file                        # 역순
sort -k2 file                       # 두 번째 필드 기준
sort -n file                        # 숫자 순

uniq

sort file | uniq                    # 중복 제거
sort file | uniq -c                 # 발생 횟수 표시
sort file | uniq -d                 # 중복만 표시

wc

wc file                             # 라인, 단어, 바이트 수
wc -l file                          # 라인 수만
wc -w file                          # 단어 수만
wc -c file                          # 바이트 수만

diff / cmp

diff file1 file2                    # 라인별 비교
cmp file1 file2                     # 바이트별 비교

효율성을 위한 팁

팁 1 – 임시 파일 대신 파이프 사용

# Instead of:
grep pattern file > temp.txt
sort temp.txt > sorted.txt

# Do:
grep pattern file | sort

팁 2 – grepawk 결합하기

# Filter then extract
grep error log.txt | awk '{print $1, $5}'

팁 3 – 여러 cut 대신 awk 사용하기

# Instead of:
cut -d: -f1 file | cut -d- -f1

# Do:
awk -F: '{print $1}' file | awk -F- '{print $1}'

팁 4 – 먼저 작은 샘플에서 패턴 테스트하기

# Test on first 10 lines
head -10 large_file.txt | grep pattern

핵심 요점

  • cut – 문자 또는 필드 추출.
  • awk – 필드 처리, 패턴 매칭, 계산.
  • grep – 패턴 검색.
  • egrep / grep -E – 확장 정규식 (여러 패턴).
  • sort, uniq, wc – 데이터 정렬, 중복 제거, 개수 세기.
  • diff / cmp – 파일 비교 (라인 vs. 바이트).

이 도구들을 파이프(|)와 결합하여 강력한 원‑라인 명령줄 워크플로를 구축하세요.

**grep** – Search multiple patterns  

**sort** – Order lines  

**uniq** – Remove duplicates (must sort first)  

**wc** – Count lines, words, bytes  

**Pipes (|)** – Chain commands together  

**diff / cmp** – Compare files  

These commands aren't just for showing off; they solve real problems:

- Analyzing logs  
- Extracting data  
- Monitoring systems  
- Processing reports  
- Debugging issues  

Master these tools and manual file searching becomes a thing of the past.  

*What text‑processing task do you do most often? Share your go‑to command combinations in the comments.*```

- 로그 분석  
- 데이터 추출  
- 시스템 모니터링  
- 보고서 처리  
- 문제 디버깅  

이 도구들을 마스터하면 수동 파일 검색은 과거의 일이 됩니다.  

*가장 자주 하는 텍스트 처리 작업은 무엇인가요? 댓글에 자주 사용하는 명령 조합을 공유해주세요.*
Back to Blog

관련 글

더 보기 »

12일간의 Shell

기사 URL: https://12days.cmdchallenge.com 댓글 URL: https://news.ycombinator.com/item?id=46190577 점수: 31 댓글: 8…