[Bash] sed

pingping·2021년 1월 24일
0
# Chap 21 - 고급 sed
  • 출처
    리눅스 커맨드라인 쉘 스크립트 바이블

[0] 이 장의 내용

  • 멀티라인 명령 사용하기
  • 대기 영역 이해하기
  • 명령을 부정형으로 바꾸기

<<<추가 예정>>>

  • 흐름 바꾸기
  • 패턴을 사용하여 바꾸기
  • 스크립트에서 sed 사용하기
  • sed 유틸리티 만들기

[1] 멀티라인 명령 보기

  • 기본 sed 편집 명령을 사용하다 보면 제약이 발생한다. 모든 sed 편집기 명령은 하나의 데이터 줄에서 기능을 수행한다.

  • sed 편집기는 여러 줄의 텍스트를 처리할 때 사용할 수 있는 3가지 특별한 명령을 포함한다.

  • N (next) : 멀티라인 그룹을 만들기 위해 데이터 스트림에서 다음 줄을 추가

  • D (delete) : 멀티라인 그룹에서 한 줄을 삭제

  • P (print) : 멀티라인 그룹의 한 줄을 인쇄


1) Prerequisite : 한 줄 버전의 다음 줄 명령 사용하기

  • 소문자 n 명령 : sed 편집기에게 명령의 시작 부분으로 돌아가지 않고 데이터 스트림 텍스트의 다음 줄로 가라고 지시한다.

Example #1

test@test:~/chap21$ cat data.txt 
This is the header line

This is a data line

This is a last line.

## 빈 줄을 제거하는 sed 스크립트를 작성할 시 모든 빈 줄이 사라진다.
test@test:~/chap21$ sed '/^$/d' data.txt 
This is the header line
This is a data line
This is a last line.

## header 패턴에 일치하는 Line을 찾아서 그 다음 라인(n)으로 가서 delete를 하는 sed 구문
test@test:~/chap21$ sed '/header/{n; d}' data.txt 
This is the header line
This is a data line

This is a last line.

2) 텍스트 줄 결합하기

  • 멀티라인 버젼을 살펴볼 것이다.

  • 멀티라인 버전의 다음 줄 명령은 이미 패턴 영역에 있는 텍스트의 다음 줄을 추가시킨다.

    ⇒ 패턴 영역에 데이터 스트림의 텍스트 2줄을 추가한 효과가 있다.

    ⇒ 텍스트의 줄은 여전히 줄바꿈 문자로 구분되지만 sed 에디터는 이제 텍스트의 두 줄을 한 줄처럼 처리할 수 있다.


Example #1

test@test:~/chap21$ cat data2.txt 
This is the header line.
This is the first line.
This is the second line.
This is the last line.

test@test:~/chap21$ sed '/first/{N; s/\n/  / }' data2.txt 
This is the header line.
This is the first line.  This is the second line.
This is the last line.
  • 동작 과정
  1. first라는 단어가 포함되어 있는 텍스트 줄을 검색한다.

  2. 그 줄과 다음줄을 결합하는 N 명령을 사용

  3. ; 는 해당 명령의 성공 유무와 상관 없이 다음 명령을 실행시킨다.

  4. s/\n/ /

    ⇒ 바꾸기 명령(switch)으로 줄바꿈 문자(\n)를 빈 칸으로 바꾼다.

  5. 그 결과 sed 편집기의 출력에서는 텍스트 파일의 두 줄이 한 줄로 표시된다.


Example #2

  • 1, 2번째 라인은 인식되지 않았고 3번째 라인만 인식되었다.
  • 2줄로 나뉘어 있는 상황에서는 일치하는 패턴을 인식하지 못한다.
test@test:~/chap21$ cat data3.txt 
On Tuesday, the Linux System
Administrator's group meeting will be held.
All System Administrators should attend.
Thank you for your attendance.

test@test:~/chap21$ sed 'N; s/System Administrator/Desktop User/' data3.txt
On Tuesday, the Linux System
Administrator`s group meeting will be held.
All Desktop Users should attend.
Thank you for your attendance.

Example #3

  • \n 줄바꿈 명령으로 해당 일치하는 패턴을 인식하도록 만들었다.
  • 그리고 일반적인 한 줄에 있는 라인도 System Admin → Desktop User 패턴을 추가하였다.
test@test:~/chap21$ sed 'N
> s/System\nAdministrator/Deskop\nUser/
> s/System Administrator/Desktop User/
> ' data3.txt
On Tuesday, the Linux Deskop
User`s group meeting will be held.
All Desktop Users should attend.
Thank you for your attendance.

Example #4

  • 하지만 텍스트의 마지막 줄에 다다르면 읽을 수 있는 다음 줄이 없으므로 N명령은 sed 편집기를 중단시킨다. 일치하는 텍스트가 데이터 스트림의 마지막 줄에 있으면 명령은 일치하는 데이터를 잡아낼 수 없다.
test@test:~/chap21$ cat data4.txt 
On Tuesday, the Linux System
Administrator's group meeting will be held.
All System Administrators should attend.

test@test:~/chap21$ sed 'N
s/System\nAdministrator/Deskop\nUser/
s/System Administrator/Desktop User/
' data4.txt

On Tuesday, the Linux Deskop
User's group meeting will be held.
All System Administrators should attend.

### 맨 아랫줄까지 인식할 수 있도록 sed 변경
### 한 줄 버전의 명령을 N 명령 앞에 옮겨 놓고 멀티라인 명령이 N명령 다음에 나타나도록 함으로써
### 이 문제를 해결할 수 있다.
test@test:~/chap21$ sed '
> s/System Administrator/Desktop User/
> N
> s/System\nAdministrator/Desktop\nUser/
> ' data4.txt

On Tuesday, the Linux Desktop
User`s group meeting will be held.
All Desktop Users should attend.

[2] 멀티라인 삭제 명령 살펴보기

  • 한 줄 버전의 삭제 명령(d)은 패턴 영역의 현재 줄을 삭제하는데 이 명령을 사용할 수 있다. N명령으로 작업하는 동안 한 줄 버전의 삭제 명령을 사용할 때는 주의해야 한다.
  • sed 편집기는 패턴 영역의 첫 번째 줄만 지우는 멀티라인 삭제 명령(D)를 제공한다.

Example #1

  • 패턴 영역에 있던 두 번째 줄은 그대로 유지된다.
test@test:~/chap21$ cat data4.txt 
On Tuesday, the Linux System
Administrator's group meeting will be held.
All System Administrators should attend.

test@test:~/chap21$ sed 'N; /System\nAdministrator/D' data4.txt 
Administrator`s group meeting will be held.
All System Administrators should attend.

Example #2

  1. ^$ (빈 줄이 있는 패턴) 라인을 패턴 영역에 추가한다.
  2. { ; } ⇒ 순차적으로 명령을 수행하겠다는 뜻이다.
  3. N : 패턴 일치하는 다음 라인 또한 패턴 영역에 추가한다.
  4. header 패턴이 있는 라인의 첫번째 줄을 D (Delete) 한다.
  5. sed {{option}} ' a / b / c ' <<text_file>> 에서 응용한 예제이다.
test@test:~/chap21$ cat data5.txt 

This is the header line.

This is the first line.

This is the last line.

test@test:~/chap21$ sed '/^$/{N; /header/D}' data5.txt 
This is the header line.

This is the first line.

This is the last line.

[3] 멀티라인 인쇄 명령 살펴보기

  • 패턴 영역의 여러 줄 가운데 첫 번째 줄만 인쇄한다.
  • 이 명령은 패턴 영역에서 줄바꿈 문자에 이를 때까지 모든 문자를 포함한다.
  • 스크립트의 출력을 억제하는 -n 옵션을 같이 사용한다.
test@test:~/chap21$ cat data3.txt 
On Tuesday, the Linux System
Administrator`s group meeting will be held.
All System Administrators should attend.
Thank you for your attendance.

test@test:~/chap21$ sed -n 'N; /System\nAdministrator/P' data3.txt
On Tuesday, the Linux System

[2] 대기 영역

  • 패턴 영역과 대기 영역을 이해할 필요가 있다.

  • 패턴 영역 : 명령을 처리하는 동안 sed 편집기가 검사할 텍스트를 보유하는 활성 버퍼 영역

  • 대기 영역 : 패턴 영역에서 텍스트의 줄을 가지고 작업하는 동안 다른 텍스트 줄을 임시로 보관하기 위한 또 다른 버퍼 영역


  • h : 패턴 영역을 대기 영역으로 복사
  • H : 패턴 영역을 대기 영역에 추가
  • g : 대기 영역을 패턴 영역으로 복사
  • G : 대기 영역을 패턴 영역에 추가
  • x : 패턴 영역과 대기 영역을 맞바꾼다.

Example #1

  1. sed 스크립트는 단어 first를 포함하는 줄을 찾기 위한 정규표현식을 사용한다
  2. 단어 first를 포함하는 줄이 나타나면 { } 안에 첫 명령인 h 명령은 이 줄을 대기 영역에 둔다.
  3. 다음 명령인 p 명령은 패턴 영역에 있는 내용을 출력하며, 이 때 패턴 영역에는 아직 첫 번째 데이터 줄이 있다.
  4. n 명령은 데이터 스트림에서 다음 줄을 가져온 다음 패턴 영역에 놓는다.
  5. p 명령은 패턴 영역의 두 번째 줄을 출력하며, 여기서는 이제 두 번째 데이터 줄이다.
  6. g 명령은 대기 영역의 내용을 패턴 영역에 놓으며, 현재 텍스트를 대체한다.
  7. p 명령은 패턴 영역의 현재 내용을 출력하며, 여기서는 다시 첫 번째 데이터 줄로 돌아온다.
test@test:~/chap21$ cat data2.txt 
This is the header line.
This is the first line.
This is the second line.
This is the last line.

test@test:~/chap21$ sed -n '/first/{h; p; n; p; g; p;}' data2.txt
This is the first line.
This is the second line.
This is the first line.

## 역순으로 출력할 수 있다.
test@test:~/chap21$ sed -n '/first/{h; n; p; g; p;}' data2.txt
This is the second line.
This is the first line.
profile
Cloud Infra Engineer & interested in python, IaC, k8s

0개의 댓글