sed

Younghwan Cha·2022년 12월 19일
0

linux

목록 보기
22/24

s: substitution

test.txt
> unix is great os. unix is opensource. unix is free os.
learn operating system.
unix linux which one you choose.
unix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

sed 's/unix/linux/' test.txt

> linux is great os. unix is opensource. unix is free os.
learn operating system.
linux linux which one you choose.
linux is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.

위와 같이 sed 명령어를 통해서 test.txt 파일에 존재하는 unix 단어를 linux 로 변경 할 수 있다.
하지만, 위에서 볼 수 있듯이 구문에서 첫번째로 매칭되는 단어(unix) 만 변경된 것을 알 수 있다.
test.txt 에 존재하는 모든 unix 단어를 linux 로 바꿔주려면 g 옵션을 사용하면 된다.

sed 's/unix/linux/g' test.txt

> linux is great os. linux is opensource. linux is free os.
learn operating system.
linux linux which one you choose.
linux is easy to learn.linux is a multiuser os.Learn linux .linux is a powerful.

같은 구문의 n 번째 매칭의 단어를 교체 ( first: /1, second: /2 )

sed 's/unix/linux/2 test.txt

unix is great os. linux is opensource. unix is free os.
learn operating system.
unix linux which one you choose.
unix is easy to learn.linux is a multiuser os.Learn unix .unix is a powerful.

n 번째 라인만 교체( 인덱스 0 부터 시작 )

sed '3 s/unix/linux test.txt

linux is great os. linux is opensource. linux is free os.
unix is great os. unix is opensource. unix is free os.
learn operating system.
linux linux which one you choose.

n 번째 match 교체

1번째로 match 하는 A 를 B 로 replace
0,/A/{s@A@B@}

https://stackoverflow.com/questions/148451/how-to-use-sed-to-replace-only-the-first-occurrence-in-a-file

마찬가지로, vim 에서도 sed 명령어를 사용 할 수 있다.

# 현재 줄 첫번째 매칭 foo 변환
:s/foo/bar/

# 현재 줄에 있는 모든 foo 변환
:s/foo/bar/g

# 파일 전체의 foo 변환
:%s/foo/bar/g

https://linuxize.com/post/vim-find-replace/

[ref]
https://www.geeksforgeeks.org/sed-command-in-linux-unix-with-examples/

profile
개발 기록

0개의 댓글