[sed] 특정 문자열 위 또는 아래에 문자열 추가하기

https://marindie.github.io/linux/Sed-Append-KR/#

sed는 스트림 에디터(stream editor)의 약자로, 문자 파일을 편집할 수 있는 강력한 도구이다. 이글에서는 sed를 사용하여 특정 문자열 위 또는 아래에 문자열을 추가하는 방법에 대해 알아본다.

sed 명령어 설명

  • /pattern/: pattern에 해당하는 텍스트를 검색한다.
  • i\text: 검색된 패턴의 위에 text를 삽입한다.
  • a\text: 검색된 패턴의 아래에 text를 삽입한다.

특정 문자열 위에 문자열을 추가하기

특정 문자열 위에 새로운 텍스트를 추가하려면 sed 명령어의 i 옵션을 사용한다.

sed -i'' -r -e "/Matching String/i\Additional strings/" file.txt 

예제

example.txt의 내용은 다음과 같다.

Hello World!!
Matching String
Good Bye!!

“Matching String” 위에 “Here is Upper Line”을 추가하는 예제이다.

$ sed -i'' -r -e "/Matching String/i\Here is Upper Line" example.txt
$ cat example.txt
Hello World!!
Here is Upper Line
Matching String
Good Bye!!

특정 문자열 아래에 문자열을 추가하기

특정 문자열 위에 새로운 텍스트를 추가하려면 sed 명령어의 a 옵션을 사용한다.

sed -i'' -r -e "/Matching String/a\Additional strings" file.txt 

예제

“Matching String” 위에 “Here is Lower Line”을 추가하는 예제이다.

$ sed -i'' -r -e "/Matching String/a\Here is Lower Line" example.txt
$ cat example.txt
Hello World!!
Here is Upper Line
Matching String
Here is Lower Line
Good Bye!!

참고 사이트

This Post Has One Comment

  1. TinyURL

    Hi, I’m Jack. Your website has become my go-to destination for expert advice and knowledge. Keep up the fantastic work!

답글 남기기