00 개요
- shell script에 겁나 많이 나옴
01 sed 명령어란
1. sed 명령어 정의
- 'stream editor'의 약자
- vi 편집기와 비슷하지만 다름
- vi는 편집기를 열어 화면과 상호작용하는 대화형 방식, sed는 명령행에서 파일을 인자로 받아 명령어를 통해 작업한 후 결과를 화면으로 확인하는 방식
- shell redirection을 이용해 편집 결과를 저장하기 전까지는 파일에 아무런 변경 가하지 않음
- 즉, 명령 수행 후 출력 결과가 원본과 다르더라도 원본에 손해가 없음
2. sed 명령어의 기능
- text를 filter하고 변환
- 입력받은 stream (파일이나 파이프라인으로부터의 입력)에 대해 기본적은 텍스트 변환을 수행함
- ed 명령어와 같이 scripted edits를 permit하는 editor와 비슷하나 sed는 works by making only one pass over the input(s)하므로 더 성능이 좋음
- 그러나 it's sed's ability to filer text in a pipeline which particularly distinguished it from other types of editors
3. sed 명령어 문법
sed [OPTION] ... {script-only-if-no-other-script} [input-file]...
02 sed 옵션
| 옵션 | 설명 |
| -n, --quiet, --silent | suppress automatic printing of pattern space - 패턴이 일치하는 라인만 출력 |
| -e script, --expression=script | add the script to the commands to be executed - 조건식 스크립트를 직접 지정 |
| -f script-file, --file=script-file | add the contents of script-file to the commands to be executed - 조건식 스크립트가 기재된 파일을 지정 |
| --follow-symlinks | follow symlinks when processing in place |
| -i[SUFFIX], --in-place[=SUFFIX] | edit files in place (makes backup if SUFFIX supplied) - 수정한 내용으로 파일 덮어쓰기 → 덮어쓰기 전의 파일을 따로 저장 가능: sed -i.bak -e '/^#/d' my.conf |
| -c, --copy | use copy instead of rename when shuffling files in -i mode |
| -b, --binary | does nothing; for compatibility with WIN32/CYGWIN/MSDOS/EMX ( open files in binary mode (CR+LFs are not treated specially)) |
| -l N, --line-length=N | specify the desired line-wrap length for the 'l' command |
| --posix | disable all GNU extensions |
| -r, --regexp-extended | use extended regular expressions in the script - 확장 정규표현을 사용한 스크립트 사용 |
| -s, --separate | consider files as separate rather than as a single continuous long stream |
| -u, --unduffered | load minimal amounts of data from the input files and flush the output buffers more often |
| -z, --null-data | separate lines by NUL characters |
| --help | display help manual and exit |
| --version | output version info and exit |
03 sed 서브 명령어 (subcommand)
| 서브명령어 | 설명 |
| a\ | 현재 행에 하나 이상의 새로운 행 추가 |
| c\ | 현재 행의 내용을 새로운 내용으로 교체 |
| d | 행 삭제 delete |
| i\ | 현재 행의 위에 텍스트 삽입 |
| h | 패턴 스페이스의 내용을 홀드 스페이스에 복사 |
| H | 패턴 그페이스의 내용을 홀드 스페이스에 추가 |
| g | 홀드 스페이스의 내용을 패턴 스페이스에 덮어쓰기 |
| G | 홀드 스페이스의 내용을 패턴 스페이스에 추가 |
| l | 출력되지 않는 특수문자를 명확하게 출력 |
| p | 행 출력 print |
| n | 다음 입력 행을 첫 번째 명령어가 아닌 다음 명령어에서 처리 |
| q | sed 종료 quit |
| r | 파일로부터 행 읽어오기 read |
| ! | 선택된 행을 제외한 나머지 전체 행에 명령어 적용 |
| s | 문자열 치환 substitute |
1. s와 함께 사용하는 치환 플래그
| flag | 설명 |
| g | 치환이 행 전체에 대해 이뤄짐 globally |
| p | 행 출력 |
| w | 파일에 쓰기 |
| x | 홀드 스페이스와 패턴 스페이스의 내용을 서로 맞바꾸기 |
| y | 한 문자를 다른 문자로 변환 (정규표현식 메타문자 사용 불가능) |
04 메타 문자
| 문자 | 설명 |
| ^ | 맨 앞 |
| $ | 맨 뒤 |
| . | 임의의 한 문자 |
| * | 직전의 문자를 0회 이상 반복 |
| + | 직전의 문자를 1회 이상 반복 |
| \? | 직전의 문자가 0회 또는 1회만 출현 |
| [ ] | 문자 클래스. [abc0-9]이면 숫자와 a, b, c 중 어떠한 한 문자를 의미 |
| | | OR. [ab|ap] 이면 ab 또는 ap |
| {3} | 직전의 문자가 3번만 출현 |
| {3, 5} | 직전의 문자가 3~5번 출현 |
| \b | 단어 구분 |
05 sed 사용 예시
# 8행부터 끝까지 출력
sed -n '8,$p' test.txt
# #로 시작하는 코멘트행 삭제
sed '/^#/d' test.txt
# 빈 행 삭제
sed '/^$/d' test.txt
# 첫 번째로 나타난 'redis' 문자를 '레디스'로 치환
sed -e 's/redis/레디스/3' test.txt
# 모든 'redis' 문자를 '레디스'로 치환
sed -e 's/redis/레디스/g' test.txt
# 대소문자 구분하지 않고 모든 'redis' 문자를 '레디스'로 치환
sed -e 's/redis/레디스/gi' test.txt
# 파일의 마지막에 내용 추가 후 기존 내용(원본) 덮어쓰기
sed -i '$a추가할내용' test.txt
# 탭을 스페이스로 변환
sed -e 's/<tab>/<space>/g' test.txt
참조
- man sed
- https://velog.io/@inhwa1025/Linux-SED-명령어-사용법
'OS 운영체제 > LINUX' 카테고리의 다른 글
| awk (텍스트 조작 명령어) (0) | 2024.09.20 |
|---|---|
| LINUX 명령어 및 연산자 (0) | 2024.08.15 |
| basename (파일 이름 명령어) (0) | 2024.06.05 |
| readlink (심볼릭 파일 경로 읽는 명령어) (0) | 2024.06.05 |
| dirname (파일 이름 제거 명령어) (0) | 2024.06.04 |