술텀뱅이 블로그

sed 사용법 본문

OS/Utility

sed 사용법

우럭망둥이 2010. 9. 12. 14:46

sed 사용법

1. sed
특징 :
① 줄 단위 작업 -> 문서 전체를 load 하지 않고 한 줄씩 메모리에 로드
따라서 아무리 큰 용량의 문서도 빠르게 잘 돌아감
② 작업 한 내용을 모니터로 출력만 함
따라서 원본파일의 내용이 수정되지 않고 오직 모니터 화면에만 출력
저장을 원할경우 > or >> (redirection)으로 저장함

2. 문법
sed s/bskim/hjsong/g filename

① / : sed 문법의 구분자
② s : 검색과 치환을 한다는 의미
③ /bskim/ : bskim이란 문자를 바꾸고 싶다.
④ /hjsong/ : 바로 전에 선택한 bskim을 hjsong으로 치환 하고싶다.
⑤ g : 차후 설명하겠음
⑥ filename : 사용할 파일 이름

# cat /test.txt
bskim is champion.
hjsong is handsom.
bskim is champion but bskim is looser.
hjsong is handsom but hjsong is looser too.
hjsong have not $money.


위와 같은 파일이 있을 때 모든 bskim을 hjsong으로 바꾸고 싶다.
# sed s/bskim/hjsong/ /test.txt
# cat /test.txt
hjsong is champion.
hjsong is handsom.
hjsong is champion but bskim is looser.
hjsong is handsom but hjsong is looser too.
hjsong have not $money.

세번째 줄의 bskim은 바뀌지 않았다.
우리가 원하는 결과가 아니다. 무엇이 문제일까?

g를 넣어서 해보겠습니다.

# sed s/bskim/hjsong/g test.txt
# cat test.txt
hjsong is champion.
hjsong is handsom.
hjsong is champion but hjsong is looser.
hjsong is handsom but hjsong is looser too.
hjsong have not $money.

g가 없다면 sed는 오직 라인에서 변경을 원하는 첫번째 bskim만을 바꾸어줌
따라서 문서 내의 모든 bskim을 hjsong으로 바꾸고 싶을 때 g를 사용하세요


3. escape 문자
지금 까지 좋았다. 그런데 특수 문자를 바꾸고 싶다.
$money를 girl로 바꾸고 싶어졌다 그래서 아래와 같이 해보았습니다.
# sed s/$money/girl/g test.txt
하지만 이상한 결과가 뜹니다.
특수문자를 바꾸고 싶다면 escape 문자인 \를 사용
# sed s/\$money/girl/g test.txt
bskim is champion.
hjsong is handsom.
bskim is champion but bskim is looser.
hjsong is handsom but hjsong is looser too.
hjsong have not girl.

4. 특정 문자를 포함한 문자열 변경
champion이란 문자가 들어간 문자열의 is를 oppa 로 바꾸고 싶을 때
# sed /champion/s/is/oppa/g test.txt
bskim oppa champion.
hjsong is handsom.
bskim oppa champion but bskim is looser.
hjsong is handsom but hjsong is looser too.
hjsong have not girl.

'OS > Utility' 카테고리의 다른 글

우분투에 gtk2.0설치  (2) 2011.03.07
vim 컬러설정 syntax on 오류와 colorscheme down  (2) 2011.03.07
Linux Portfowarding IPtable  (2) 2011.03.07
Linux Port forwarding IPtable  (1) 2011.03.07
Comments