C.W.K.
Stream
Lesson 03 of 10 · published

sed — Stream Editor

~15 min · sed, substitute, in-place

Level 0창 구경꾼
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

s/from/to/ 엔진

sed 가 입력의 각 줄에 작은 프로그램을 적용해서 결과 출력. 가장 흔한 command 는 s/pattern/replacement/ — substitute. 한 번 써보면 GUI 에디터에서 찾아바꾸기 다시는 안 함.

치환

  • sed 's/foo/bar/' — 줄당 첫 매치.
  • sed 's/foo/bar/g' — 모든 매치 (global).
  • sed 's/foo/bar/I' — 대소문자 무시 (GNU).
  • sed 's|/usr/local|/opt|g' — 경로 치환할 때 구분자 변경 (아무 한 글자 OK).
  • sed -E 's/(foo|bar)/[\1]/g' — extended regex + 캡처. \1 가 첫 캡처 그룹.

다른 command

  • sed '/pattern/d' — 매치 줄 삭제.
  • sed -n '5,10p' file — 5-10 번째 줄만 출력 (-n 이 기본 출력 끔).
  • sed '$d' file — 마지막 줄 삭제.
  • sed '1i\\ header' file — 1 번째 줄에 텍스트 삽입.

In-place 편집

sed -i 가 파일 자체 수정. BSD sed (macOS) 는 빈 argument 가 필요: sed -i '' 's/foo/bar/g' file. GNU sed: sed -i 's/foo/bar/g' file. 처음 보면 누구나 헷갈려. 일관성 원하면 brew install gnu-sed + alias.

sed vs awk vs perl

sed = 줄 단위 치환. awk = 필드 인식 처리. perl -pe = 진지한 regex (lookahead 포함 풀 PCRE). 각자 자리 있음. sed 는 가장 작고 portable.

Code

치환 패턴·bash
# Replace foo with bar globally, output to stdout
sed 's/foo/bar/g' file.txt
# In place — macOS BSD
sed -i '' 's/foo/bar/g' file.txt
# In place — GNU (linux or brew install gnu-sed)
sed -i 's/foo/bar/g' file.txt
# Slash in pattern? change delimiter
sed 's|/usr/local|/opt/homebrew|g' install.sh
삭제 + 추출·bash
# Drop blank lines
sed '/^$/d' file
# Print only lines 100-110
sed -n '100,110p' big.log
# Strip trailing whitespace
sed -E 's/[[:space:]]+$//' file

External links

Exercise

~/.zshrc/tmp/zshrc.bak 으로 복사. sed -n '1,10p' /tmp/zshrc.bak 확인. sed 's/^export/EXPORT/' /tmp/zshrc.bak | head. 마지막으로 in-place: mac sed -i '' 's/EXPORT/export/' /tmp/zshrc.bak, linux sed -i 's/EXPORT/export/' /tmp/zshrc.bak.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.