웹사이트 검색

Sed Stream Editor를 사용하여 Linux에서 텍스트를 조작하는 기본 사항


소개

스트림 편집기의 줄임말인 sed 명령은 표준 입력 또는 파일에서 오는 텍스트에 대한 편집 작업을 수행합니다. sed는 라인별로 비대화형 방식으로 편집합니다.

즉, 명령을 호출할 때 모든 편집 결정을 내리고 sed가 지시 사항을 자동으로 실행합니다. 이것은 혼란스럽거나 직관적이지 않은 것처럼 보일 수 있지만 특히 스크립트 또는 자동화된 워크플로의 일부로 텍스트를 변환하는 매우 강력하고 빠른 방법입니다.

이 자습서에서는 몇 가지 기본 작업을 다루고 이 편집기를 작동하는 데 필요한 구문을 소개합니다. 일반 텍스트 편집기를 sed로 대체하지는 않겠지만, 텍스트 편집 도구 상자에 환영받는 추가 기능이 될 것입니다.

참고: 이 튜토리얼은 Ubuntu 및 기타 Linux 운영 체제에서 발견되는 sed의 GNU 버전을 사용합니다. macOS를 사용하는 경우 옵션과 인수가 다른 BSD 버전이 있습니다. brew install gnu-sed를 사용하여 Homebrew와 함께 sed의 GNU 버전을 설치할 수 있습니다.

기본 사용법

sed는 텍스트 파일이나 표준 입력(STDIN)에서 읽는 텍스트 스트림에서 작동합니다. 즉, 편집을 위해 다른 명령의 출력을 sed로 직접 보내거나 이미 만든 파일에서 작업할 수 있습니다.

또한 sed는 기본적으로 모든 것을 표준 출력(STDOUT)으로 출력합니다. 즉, 리디렉션되지 않는 한 sed는 출력을 파일에 저장하는 대신 화면에 출력합니다.

기본 사용법은 다음과 같습니다.

  1. sed [options] commands [file-to-edit]

이 자습서에서는 BSD 소프트웨어 라이선스 사본을 사용하여 sed를 실험합니다. Ubuntu에서 작업할 수 있도록 다음 명령을 실행하여 BSD 라이선스 파일을 홈 디렉터리에 복사합니다.

  1. cd
  2. cp /usr/share/common-licenses/BSD .

BSD 라이선스의 로컬 사본이 없는 경우 다음 명령을 사용하여 직접 만드십시오.

  1. cat << 'EOF' > BSD
  2. Copyright (c) The Regents of the University of California.
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions
  6. are met:
  7. 1. Redistributions of source code must retain the above copyright
  8. notice, this list of conditions and the following disclaimer.
  9. 2. Redistributions in binary form must reproduce the above copyright
  10. notice, this list of conditions and the following disclaimer in the
  11. documentation and/or other materials provided with the distribution.
  12. 3. Neither the name of the University nor the names of its contributors
  13. may be used to endorse or promote products derived from this software
  14. without specific prior written permission.
  15. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  16. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  18. ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  19. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  21. OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  22. HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  23. LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  24. OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  25. SUCH DAMAGE.
  26. EOF

sed를 사용하여 BSD 라이센스 파일의 내용을 봅시다. sed는 기본적으로 결과를 화면에 보냅니다. 즉, 편집 명령을 전달하지 않고 파일 판독기로 사용할 수 있습니다. 다음 명령을 실행해 보십시오.

  1. sed '' BSD

화면에 BSD 라이센스가 표시됩니다.

Output
Copyright (c) The Regents of the University of California. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. ... ...

작은따옴표에는 sed에 전달하는 편집 명령이 포함됩니다. 이 경우 아무 것도 전달하지 않았으므로 sed는 수신한 각 줄을 표준 출력으로 인쇄했습니다.

sed는 파일이 아닌 표준 입력을 사용할 수 있습니다. cat 명령의 출력을 sed로 파이프하여 동일한 결과를 생성합니다.

  1. cat BSD | sed ''

파일의 출력이 표시됩니다.

Output
Copyright (c) The Regents of the University of California. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. . . . . . .

보시다시피 파이프 (|) 문자로 출력을 파이핑할 때 생성되는 것과 같이 파일이나 텍스트 스트림에서 작업할 수 있습니다.

인쇄 라인

이전 예제에서 작업 없이 sed로 전달된 입력이 결과를 표준 출력으로 직접 인쇄하는 것을 보았습니다.

작은따옴표 안에 p 문자를 사용하여 지정하는 sed의 명시적 print 명령을 살펴보겠습니다.

다음 명령을 실행합니다.

  1. sed 'p' BSD

BSD 파일의 각 줄이 두 번 인쇄되는 것을 볼 수 있습니다.

Output
Copyright (c) The Regents of the University of California. Copyright (c) The Regents of the University of California. All rights reserved. All rights reserved. Redistribution and use in source and binary forms, with or without Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions modification, are permitted provided that the following conditions are met: are met: . . . . . .

sed는 기본적으로 각 줄을 자동으로 인쇄한 다음 "p\ 명령을 사용하여 명시적으로 줄을 인쇄하도록 지시했기 때문에 각 줄이 두 번 인쇄됩니다.

출력을 자세히 살펴보면 첫 번째 줄이 두 번 있고 두 번째 줄이 두 번 나오는 등 sed가 한 줄씩 데이터에서 작동한다는 것을 알 수 있습니다. 라인을 읽고 작업을 수행한 후 다음 라인에서 프로세스를 반복하기 전에 결과 텍스트를 출력합니다.

자동 인쇄를 억제하는 sed-n 옵션을 전달하여 결과를 정리할 수 있습니다.

  1. sed -n 'p' BSD
Output
Copyright (c) The Regents of the University of California. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. . . . . . .

이제 각 줄을 한 번 인쇄하는 것으로 돌아갑니다.

지금까지의 예제는 편집으로 간주하기 어렵습니다(각 행을 두 번 인쇄하지 않는 한...). 다음으로 sed가 텍스트 데이터의 특정 섹션을 대상으로 하여 출력을 수정하는 방법을 살펴보겠습니다.

주소 범위 사용

주소를 사용하면 텍스트 스트림의 특정 부분을 타겟팅할 수 있습니다. 특정 라인 또는 라인 범위를 지정할 수 있습니다.

sed가 파일의 첫 줄을 출력하도록 합시다. 다음 명령을 실행합니다.

  1. sed -n '1p' BSD

첫 번째 줄은 화면에 인쇄됩니다.

Output
Copyright (c) The Regents of the University of California.

인쇄 명령 앞에 숫자 1을 배치하여 작업할 줄 번호를 sed에 알렸습니다. 다섯 줄을 쉽게 인쇄할 수 있습니다("-n”을 잊지 마세요).

  1. sed -n '1,5p' BSD

다음 출력이 표시됩니다.

Output
Copyright (c) The Regents of the University of California. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions

방금 sed에 주소 범위를 지정했습니다. sed에 주소를 지정하면 해당 행에 따르는 명령만 수행합니다. 이 예에서는 sed에게 1행부터 5행까지 인쇄하도록 지시했습니다. 첫 번째 주소를 제공한 다음 오프셋을 사용하여 다음과 같이 이동할 추가 행 수를 sed에 알리는 방식으로 이를 지정할 수 있습니다.

  1. sed -n '1,+4p' BSD

sed에 1행에서 시작하여 다음 4행에서도 작동하도록 지시했기 때문에 결과는 동일합니다.

줄 걸러 인쇄하려면 ~ 문자 뒤에 간격을 지정하십시오. 다음 명령은 BSD 파일에서 라인 1부터 시작하여 다른 모든 라인을 인쇄합니다.

  1. sed -n '1~2p' BSD

표시되는 출력은 다음과 같습니다.

Output
Copyright (c) The Regents of the University of California. modification, are permitted provided that the following conditions 1. Redistributions of source code must retain the above copyright 2. Redistributions in binary form must reproduce the above copyright documentation and/or other materials provided with the distribution. may be used to endorse or promote products derived from this software . . . . . .

sed를 사용하여 출력에서 텍스트를 삭제할 수도 있습니다.

텍스트 삭제

p 명령을 d 명령으로 변경하여 이전에 텍스트 인쇄를 지정했던 위치에서 텍스트 삭제를 수행할 수 있습니다.

이 경우 sed가 삭제되지 않은 모든 항목을 인쇄하기 때문에 더 이상 -n 명령이 필요하지 않습니다. 이것은 당신이 무슨 일이 일어나고 있는지 보는 데 도움이 될 것입니다.

이전 섹션의 마지막 명령을 수정하여

  1. sed '1~2d' BSD

그 결과 지난 번에 제공되지 않은 모든 라인이 표시됩니다.

Output
All rights reserved. Redistribution and use in source and binary forms, with or without are met: notice, this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer in the 3. Neither the name of the University nor the names of its contributors without specific prior written permission. . . . . . .

소스 파일이 영향을 받지 않는다는 점에 유의하는 것이 중요합니다. 그것은 여전히 손상되지 않았습니다. 편집 내용이 화면에 출력됩니다.

편집 내용을 저장하려면 다음과 같이 표준 출력을 파일로 리디렉션할 수 있습니다.

  1. sed '1~2d' BSD > everyother.txt

이제 cat로 파일을 엽니다.

  1. cat everyother.txt

이전에 화면에서 본 것과 동일한 출력이 표시됩니다.

Output
All rights reserved. Redistribution and use in source and binary forms, with or without are met: notice, this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer in the 3. Neither the name of the University nor the names of its contributors without specific prior written permission. . . . . . .

sed 명령은 기본적으로 소스 파일을 편집하지 않지만 "제자리에서 편집 수행\을 의미하는 -i 옵션을 전달하여 이 동작을 변경할 수 있습니다. 그러면 소스 파일이 변경됩니다.

경고: -i 스위치를 사용하면 원본 파일을 덮어쓰므로 주의해서 사용해야 합니다. 먼저 -i 스위치 없이 작업을 수행한 다음 원하는 것이 있으면 -i를 사용하여 명령을 다시 실행하거나 원본 파일의 백업을 만들거나 파일로 출력합니다. -i 스위치를 사용하여 실수로 원본 파일을 변경하는 것은 매우 쉽습니다.

방금 만든 everyother.txt 파일을 제자리에서 편집하여 사용해 봅시다. 다른 모든 줄을 삭제하여 파일을 더 줄이겠습니다.

  1. sed -i '1~2d' everyother.txt

cat을 사용하여 cat everyother.txt가 있는 파일을 표시하면 파일이 편집된 것을 볼 수 있습니다.

-i 옵션은 위험할 수 있습니다. 고맙게도 sed는 편집하기 전에 백업 파일을 생성할 수 있는 기능을 제공합니다.

편집하기 전에 백업 파일을 만들려면 "-i” 옵션 바로 뒤에 백업 확장자를 추가하십시오.

  1. sed -i.bak '1~2d' everyother.txt

이렇게 하면 .bak 확장자를 가진 백업 파일이 생성된 다음 원본 파일을 제자리에서 편집합니다.

다음으로 sed를 사용하여 검색 및 바꾸기 작업을 수행하는 방법을 살펴보겠습니다.

텍스트 대체

아마도 sed의 가장 잘 알려진 용도는 대체 텍스트일 것입니다. sed는 정규 표현식을 사용하여 텍스트 패턴을 검색한 다음 찾은 텍스트를 다른 것으로 바꿀 수 있습니다.

Grep 정규식을 사용하여 Linux에서 텍스트 패턴 검색에 따라 정규식에 대해 자세히 알아볼 수 있습니다.

가장 기본적인 형태로 다음 구문을 사용하여 한 단어를 다른 단어로 변경할 수 있습니다.

's/old_word/new_word/'

s는 대체 명령입니다. 세 개의 슬래시(/)는 서로 다른 텍스트 필드를 구분하는 데 사용됩니다. 더 도움이 될 경우 다른 문자를 사용하여 필드를 구분할 수 있습니다.

예를 들어 웹 사이트 이름을 변경하려는 경우 URL에 슬래시가 포함되어 있으므로 다른 구분 기호를 사용하는 것이 도움이 됩니다.

다음 명령을 실행하여 echo로 URL을 인쇄하고 밑줄(_) 문자를 구분 기호로 사용하여 sed로 수정합니다.

  1. echo "http://www.example.com/index.html" | sed 's_com/index_org/home_'

이것은 com/indexorg/home으로 대체합니다. 출력에 수정된 URL이 표시됩니다.

Output
http://www.example.org/home.html

마지막 구분 기호를 잊지 마십시오. 그렇지 않으면 sed가 불평합니다. 이 명령을 실행한 경우:

  1. echo "http://www.example.com/index.html" | sed 's_com/index_org/home'

다음 출력이 표시됩니다.

Output
sed: -e expression #1, char 20: unterminated `s' command

몇 가지 대체를 연습하기 위해 새 파일을 만들어 봅시다. 다음 명령을 실행하여 song.txt라는 새 텍스트 파일을 만듭니다.

  1. echo "this is the song that never ends
  2. yes, it goes on and on, my friend
  3. some people started singing it
  4. not knowing what it was
  5. and they'll continue singing it forever
  6. just because..." > song.txt

이제 on 표현식을 forward로 대체하겠습니다. 다음 명령을 사용합니다.

  1. sed 's/on/forward/' song.txt

출력은 다음과 같습니다.

Output
this is the sforwardg that never ends yes, it goes forward and on, my friend some people started singing it not knowing what it was and they'll cforwardtinue singing it forever just because...

여기에서 몇 가지 주목할만한 사항을 볼 수 있습니다. 첫째, sed가 단어가 아닌 패턴을 대체했다는 것입니다. 노래 내의 onforward로 변경됩니다.

주목해야 할 다른 사항은 2행에서 두 번째 onforward로 변경되지 않았다는 것입니다.

기본적으로 s 명령은 줄의 첫 번째 일치 항목에서 작동한 후 다음 줄로 이동하기 때문입니다. sed가 각 줄의 첫 번째 인스턴스 대신 on의 모든 인스턴스를 바꾸도록 하려면 대체 명령에 선택적 플래그를 전달해야 합니다.

g 플래그를 대체 세트 뒤에 배치하여 대체 명령에 제공하십시오.

  1. sed 's/on/forward/g' song.txt

다음 출력이 표시됩니다.

Output
this is the sforwardg that never ends yes, it goes forward and forward, my friend some people started singing it not knowing what it was and they'll cforwardtinue singing it forever just because...

이제 대체 명령은 모든 인스턴스를 변경합니다.

sed가 각 줄에서 찾은 "on\의 두 번째 인스턴스를 변경하려는 경우 g< 대신 숫자 2를 사용합니다. /코드>:

  1. sed 's/on/forward/2' song.txt

이번에는 두 번째 항목이 없으므로 다른 줄은 변경되지 않습니다.

Output
this is the song that never ends yes, it goes on and forward, my friend some people started singing it not knowing what it was and they'll continue singing it forever just because...

대체된 행만 보려면 -n 옵션을 다시 사용하여 자동 인쇄를 억제하십시오.

그런 다음 대체 명령에 p 옵션을 전달하여 대체가 발생한 행을 인쇄할 수 있습니다.

  1. sed -n 's/on/forward/2p' song.txt

변경된 줄이 화면에 인쇄됩니다.

Output
yes, it goes on and forward, my friend

보시다시피 명령 끝에 플래그를 결합할 수 있습니다.

검색 프로세스에서 대소문자를 무시하도록 하려면 "i\ 플래그를 전달하면 됩니다.

  1. sed 's/SINGING/saying/i' song.txt

표시되는 출력은 다음과 같습니다.

Output
this is the song that never ends yes, it goes on and on, my friend some people started saying it not knowing what it was and they'll continue saying it forever just because...

일치하는 텍스트 교체 및 참조

정규식을 사용하여 더 복잡한 패턴을 찾으려는 경우 대체 텍스트에서 일치하는 패턴을 참조하는 다양한 방법이 있습니다.

예를 들어 줄 시작 부분부터 at까지 일치시키려면 다음 명령을 사용하십시오.

  1. sed 's/^.*at/REPLACED/' song.txt

다음 출력이 표시됩니다.

Output
REPLACED never ends yes, it goes on and on, my friend some people started singing it REPLACED it was and they'll continue singing it forever just because...

와일드카드 표현식이 줄의 시작부터 at의 마지막 인스턴스까지 일치하는 것을 볼 수 있습니다.

검색 문자열에서 일치할 정확한 구문을 모르기 때문에 & 문자를 사용하여 대체 문자열에서 일치하는 텍스트를 나타낼 수 있습니다.

일치하는 텍스트 주위에 괄호를 넣어 보겠습니다.

  1. sed 's/^.*at/(&)/' song.txt

다음 출력이 표시됩니다.

Output
(this is the song that) never ends yes, it goes on and on, my friend some people started singing it (not knowing what) it was and they'll continue singing it forever just because...

일치하는 텍스트를 참조하는 보다 유연한 방법은 이스케이프 처리된 괄호를 사용하여 일치하는 텍스트 섹션을 그룹화하는 것입니다.

괄호로 표시된 모든 검색 텍스트 그룹은 이스케이프된 참조 번호로 참조할 수 있습니다. 예를 들어, 첫 번째 괄호 그룹은 로, 두 번째 괄호 그룹은 등으로 참조할 수 있습니다.

이 예에서는 각 줄의 처음 두 단어를 전환합니다.

  1. sed 's/\([a-zA-Z0-9][a-zA-Z0-9]*\) \([a-zA-Z0-9][a-zA-Z0-9]*\)/\2 \1/' song.txt

다음 출력이 표시됩니다.

Output
is this the song that never ends yes, goes it on and on, my friend people some started singing it knowing not what it was they and'll continue singing it forever because just...

보시다시피 결과가 완벽하지 않습니다. 예를 들어, 두 번째 줄은 문자 집합에 나열되지 않은 문자가 있기 때문에 첫 번째 단어를 건너뜁니다. 마찬가지로 다섯 번째 줄에서 theyll을 두 단어로 처리했습니다.

정규 표현식을 더 정확하게 개선해 보겠습니다.

  1. sed 's/\([^ ][^ ]*\) \([^ ][^ ]*\)/\2 \1/' song.txt

다음 출력이 표시됩니다.

Output
is this the song that never ends it yes, goes on and on, my friend people some started singing it knowing not what it was they'll and continue singing it forever because... just

이것은 지난번보다 훨씬 낫습니다. 연결된 단어로 문장 부호를 그룹화합니다.

괄호 안에서 표현식을 반복하는 방법에 주목하십시오(* 문자 없이 한 번, 그 다음에는 문자로 한 번). 이는 * 문자가 그 앞에 오는 문자 집합과 0번 이상 일치하기 때문입니다. 이는 패턴이 발견되지 않더라도 와일드카드와의 일치가 \일치\로 간주됨을 의미합니다.

sed가 텍스트를 한 번 이상 찾도록 하려면 와일드카드를 사용하기 전에 와일드카드 없이 한 번 일치시켜야 합니다.

결론

이 자습서에서는 sed 명령을 살펴보았습니다. 파일에서 특정 줄을 인쇄하고, 텍스트를 검색하고, 줄을 삭제하고, 원본 파일을 덮어쓰고, 정규식을 사용하여 텍스트를 바꿉니다. 적절하게 구성된 sed 명령을 사용하여 텍스트 문서를 빠르게 변환하는 방법을 이미 볼 수 있어야 합니다.

이 시리즈의 다음 기사에서는 몇 가지 고급 기능을 살펴봅니다.