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

파일 인코딩

~10 min · utf-8, encoding, bom, line-endings

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

바이트 vs 글자

파일은 바이트. 도구는 그 바이트가 글자를 인코딩한다고 가정. 인코딩 (UTF-8, UTF-16, ISO-8859-1) 마다 같은 바이트를 다른 글자로 해석. 가정이 깨지면 mojibake (ëëë) 나 에러.

인코딩 감지

file --mime-encoding file.txt   # GNU + macOS
iconv -f UTF-8 -t UTF-8 file.txt >/dev/null # 에러 나면 UTF-8 아님

변환

iconv -f ISO-8859-1 -t UTF-8 in.txt > out.txt
iconv -f UTF-16 -t UTF-8 win.txt > mac.txt

BOM — 보이지 않는 적

UTF-8 with BOM 은 파일 앞에 3 바이트 (EF BB BF) 를 붙여. 대부분 모던 도구가 처리하지만 일부는 못 해서 시작에 이상한 글자가 보여. 제거: sed -i '1s/^\xef\xbb\xbf//' file (linux GNU) 또는 perl -i -pe 's/^\x{FEFF}//' file.

줄바꿈

  • Unix (LF) — \n.
  • Windows (CRLF) — \r\n.
  • 옛 Mac (CR) — \r. 거의 멸종.

변환: tr -d '\r' < in.txt > out.txt 또는 dos2unix file (brew install dos2unix). OS 간 공유 파일의 버그 다수가 줄바꿈에서 옴.

왜 중요한가

$ 같은 regex 는 줄 끝 = \n 가정. 파일이 CRLF 면 매치된 끝 글자에 \r 가 슬쩍 포함. 개발 머신에선 테스트 통과, Windows 거쳐 CI 가면 실패.

Code

인코딩 워크플로·bash
file --mime-encoding mystery.txt
iconv -f ISO-8859-1 -t UTF-8 mystery.txt > clean.txt
# Strip CRLF
tr -d '\r' < windows.txt > unix.txt
# Strip a BOM
perl -i -pe 's/^\x{FEFF}//' file.txt

External links

Exercise

file --mime-encoding ~/.zshrc — UTF-8 확인. CRLF 파일 만들기: printf 'line1\r\nline2\r\n' > /tmp/win.txt; file /tmp/win.txt. 변환: tr -d '\r' < /tmp/win.txt > /tmp/unix.txt; file /tmp/unix.txt.

Progress

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

댓글 0

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

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