Welcome to Our Website

의 기초를 사용하여 나오 스트림 편집기 텍스트를 조작하기 리눅스에서

소개

sed명령의 짧은 스트림 편집기,수행에 대한 편집 작업을 텍스트에서 오는 표준 입력이나 파일입니다. sed는 라인별로 그리고 비 대화식 방식으로 편집합니다.

이것은 당신의 편집을 결정으로 당신은 당신 명령을 호출하고sed실행 방향을 자동으로 합니다., 이것은 복잡하게 보일지도 모른거나 비직관적이지만,그것은 매우 강력하고 빠른 방법을 변환하는 텍스트,특히 스크립트의 일부로 또는 자동화된 워크플로우.

이 튜토리얼에서는 몇 가지 기본 작업을 다루고이 편집기를 작동시키는 데 필요한 구문을 소개합니다. 당신은 거의 확실히 대체하지 않는 일반 텍스트 편집기sed지만,그것은 아마가 환영한 텍스트 편집 도구.

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

대화 형 터미널을 시작하십시오!

기본 사용법

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

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

기본적인 사용가:

  • sed commands

이 튜토리얼에서 당신의 사본을 사용 BSD 소프트웨어 라이센스를 실험과 함께sed., 우분투에서 다음 명령을 실행합 복사하 BSD 라이센스 파일이 귀하의 홈디렉토리도록 당신이 그것으로 작업 할 수 있습니다:

  • cd
  • cp /usr/share/common-licenses/BSD .

없는 경우에는 로컬 사본 BSD license,하나의 자신을 만들이 명령:

  • cat << 'EOF' > BSD
  • 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.
  • 3. Neither the name of the University nor the names of its contributors
  • may be used to endorse or promote products derived from this software
  • without specific prior written permission.
  • THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  • ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  • IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  • ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  • FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  • DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  • OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  • HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  • LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  • OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  • SUCH DAMAGE.
  • EOF

자의 사용sed의 내용을 보려면 BSD 라이센스 파일입니다. sed보내는 결과를 화면에 기본적으로 사용할 수 있다는 것을 의미 파일로 리더 전달하여 그것은 아무 편집 명령입니다., 을 실행하여 다음과 같은 명령:

  • sed '' BSD

당신이 볼 수 BSD license 화면에 표시됩니다.

Output
Copyright (c) The Regents of the University of California.All rights reserved.Redistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditionsare 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를 생산 같은 결과:

  • 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 withoutmodification, are permitted provided that the following conditionsare 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‘s explicitprint명령을 사용하여 지정한p문자 내에서 단일세.

다음 명령을 실행합니다.

  • 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 withoutRedistribution and use in source and binary forms, with or withoutmodification, are permitted provided that the following conditionsmodification, are permitted provided that the following conditionsare met:are met:. . .. . .

sed자동으로 인쇄는 각 라인에 의해 기본적으로 그리고 당신은 말 그것을 인쇄 라인을 사용하여 명시적으로”p”명령을 얻을 수 있도록,각 라인에 인쇄된다.,

경우 출력을 검사합 밀접하는 것을 볼 수 있는 첫 번째 두 번 라인에 의해 다음,두 번째 라인에 두 번,등등을 알려주는sed에서 작동 데이터 라인으로 라인. 그것은 라인을 읽고,그것에 작동하고,다음 줄에 프로세스를 반복하기 전에 결과 텍스트를 출력합니다.

정리할 수 있는 결과를 전달하여-n옵션을sed,를 표시하지 않는 자동 인쇄

  • 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 withoutmodification, are permitted provided that the following conditionsare 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가 텍스트 데이터의 특정 섹션을 타겟팅하여 출력을 수정할 수있는 방법을 살펴 보겠습니다.

주소 범위를 사용하여

주소를 사용하면 텍스트 스트림의 특정 부분을 대상으로 지정할 수 있습니다. 특정 선 또는 심지어 선의 범위를 지정할 수 있습니다.

let’s havesed파일의 첫 번째 줄을 인쇄하십시오., 다음 명령을 실행합니다.

  • sed -n '1p' BSD

첫 번째 라인 인쇄 화면:

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

배치하여 수를1하기 전에 인쇄 명령을 말sed줄 번호를 운영하다. 당신은 쉽게 다섯 개의 인쇄 라인을 잊지 않는다(“n”):

  • 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 withoutmodification, are permitted provided that the following conditions

당신은 단지 주소의 범위를sed., sed주소를 지정하면 해당 줄에 따르는 명령 만 수행합니다. 이 예제에서는 sed 에 1 행에서 5 행을 인쇄하도록 지시했습니다. 지정할 수도 있습니다 이는 다른 방법으로 제공하여 첫 번째 주소를 사용한 오프셋을 말 sed 얼마나 많은 추가적인 선 여행은 다음과 같습니다.

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

이와 같은 출력기 때문에,너에게 말했sed를 시작하는 라인 1 에서와 그런 다음 운영에 다음 4 개선뿐만 아니라.,

다른 모든 줄을 인쇄하려면~문자 뒤에 간격을 지정하십시오. 다음과 같은 명령어는 다른 모든 선BSD파일을 시작으로 line1:

  • sed -n '1~2p' BSD

여기에 출력을 볼 수 있습니다:

Output
Copyright (c) The Regents of the University of California.modification, are permitted provided that the following conditions1. Redistributions of source code must retain the above copyright2. 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명령입니다.

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

수정 마지막 명령은 이전 섹션에서 그것을
삭제 다른 모든 라인을 시작으로 첫 번째

  • sed '1~2d' BSD

결과는 당신이 볼 모든 라인 당신이 주어지지 않는 마지막 시간:

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

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

경우 우리는 저장하려는 우리의 편집하고,우리가 할 수 있습 리디렉션에 표준 출력 파일에 다음과 같이

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

이제 파일을 열과 함께cat

  • cat everyother.txt

당신이 볼 같은 출력하는 당신에 보면 이전에는:

Output
All rights reserved.Redistribution and use in source and binary forms, with or withoutare met: notice, this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer in the3. 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파일을 편집하여 시도해 보겠습니다., 하자 더욱 줄이기 위해 파일을 삭제하여 다른 모든 선
다.

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

사용하는 경우cat을 표시하는 파일과 함께cat everyother.txt,당신이 볼 수 있는 파일을 편집 할 수 있습니다.

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

백업 파일을 만들기 전에 편집,추가 백업 확장을 직접 후”-i”옵션:

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

이 백업 파일을 만드는.bakextension,다음 편집 원본 파일에 있습니다.

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

대체 텍스트

아마도 가장 잘 알려진 사용을 위한sed는 대체 텍스트입니다., sed할 수 있는 텍스트 검색 패턴을 정규 표현식을 사용하여,그리고 다음 대체 텍스트와 다른 뭔가가 있습니다.

에 대해 자세히 알아볼 수 있습니다 정규 표현식에 의해 다음 사용하 Grep 정규 표현식을 텍스트 검색 패턴 리눅스에서.

에서 그것의 가장 기본적인 형태를 변경할 수 있습 중 하나는 단어를 사용하는 다른 단어는 구문은 다음과 같습니다.

's/old_word/new_word/'

s는 대체 명령입니다. 세 개의 슬래시(/)는 다른 텍스트 필드를 분리하는 데 사용됩니다., 더 도움이 될 경우 필드를 구분하기 위해 다른 문자를 사용할 수 있습니다.예를 들어 웹 사이트 이름을 변경하려는 경우 Url 에 슬래시가 포함되어 있으므로 다른 구분 기호를 사용하는 것이 도움이 될 것입니다.

다음 명령을 실행하여 인쇄하여 URL 을echo고 수정하는것과 함께sed를 사용하여,밑줄(_)문자로 구분 기호:

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

이를 대체com/indexorg/home., 출력을 보여줍 수정 된 URL:

Output

Do not forget the final delimiter, or sed will complain. If you ran this command:

  • 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

  • echo "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..." > song.txt

지자체 식onforward. 다음 명령어를 사용합니다.

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

출력은 다음과 같습니다:

Output
this is the sforwardg that never endsyes, it goes forward and on, my friendsome people started singing itnot knowing what it wasand they'll cforwardtinue singing it foreverjust because...

당신이 볼 수있는 몇 가지 주목할만한 일들이 여기에 있습니다., 첫째,sed가 단어가 아닌 패턴을 대체했다는 것입니다. on내의songforward로 변경됩니다.

다른 것을 알 수 있는 라인에서 2 번째on변경되지 않았습을forward.

이 때문에 기본적으로s명령에서 작동하는 첫 번째 매치에서 선한 다음 이동됩니다., 을sed대체의 모든 인스턴스on대신에 첫 번째는 각 라인,당신이 통과해야 하는 옵션 플래그를 대체 명령입니다.

을 제공하는g플래그를 대체 명령을 배치하여 대체 한 후 설정한다.

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

이 출력:

Output
this is the sforwardg that never endsyes, it goes forward and forward, my friendsome people started singing itnot knowing what it wasand they'll cforwardtinue singing it foreverjust because...

이제는 대체 명령 모든 변경 사항 인스턴스입니다.,

경우에만 변경하고 싶어 두 번째 인스턴스의”on”sed 에서 찾는 각 라인,당신은 번호를 사용하는2대신g

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

이번에 다른 선은 변경되지 않은,그들이 없는 두 번째 항목은:

Output
this is the song that never endsyes, it goes on and forward, my friendsome people started singing itnot knowing what it wasand they'll continue singing it foreverjust because...

경우만 보고 싶어하는 선체,사용하는-n옵션을 억제 자동 인쇄.,

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

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

선 변경된 것 인쇄 화면:

Output
yes, it goes on and forward, my friend

당신이 볼 수있는 결합할 수 있습니다 플래그의 끝에서 명령입니다.

검색 프로세스가 대소 문자를 무시하려면”i”플래그를 전달할 수 있습니다.,

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

여기에 출력을 볼 수 있습니다:

Output
this is the song that never endsyes, it goes on and on, my friendsome people started saying itnot knowing what it wasand they'll continue saying it foreverjust because...

대체과를 참조치 Text

을 찾으려면 더 복잡한 패턴으로 정규 표현식을,당신은 당신의 번호를 가지의 다른 방법을 참조하여 일치하는 패턴으로 대체 텍스트입니다.,

예를 들어,일부터 시작 부분의 라인을at,다음 명령어를 사용합니다.

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

이 출력:

Output
REPLACED never endsyes, it goes on and on, my friendsome people started singing itREPLACED it wasand they'll continue singing it foreverjust because...

당신이 볼 수 있는 와일드카드 표현과 일치하에서 시작 부분의 라인의 마지막 인스턴스at.

지 않기 때문에 알고 정확한 구문과 일치하는 검색에 문자열을 사용할 수 있습니다&문자를 나타내서 일치하는 텍스트에서 교체 문자열입니다.,

의 괄호를 넣어 주위에 일치하는 텍스트:

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

이 출력:

Output
(this is the song that) never endsyes, it goes on and on, my friendsome people started singing it(not knowing what) it wasand they'll continue singing it foreverjust because...

더 유연한 사고 방식을 참조하치의 텍스트를 사용하는 것입을 탈출하기 위해 괄호는 그룹 섹션의 일치하는 텍스트입니다.

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

이 예제에서는,우리 스위치 처음 두 단어는 각각의 라인:

  • sed 's/\(*\) \(*\)/\2 \1/' song.txt

이 출력:

Output
is this the song that never endsyes, goes it on and on, my friendpeople some started singing itknowing not what it wasthey and'll continue singing it foreverbecause just...

당신이 볼 수 있듯이,결과는 완벽하지 않습니다. 예를 들면,두 번째 라인을 건너뜁 첫 번째 단어가 있기 때문에 문자에 나열되지 않은 우리의 문자 집합입니다. 마찬가지로they'll를 다섯 번째 줄의 두 단어로 처리했습니다.

의 개선을 위한 정규 표현식에 더 정확:

  • sed 's/\(*\) \(*\)/\2 \1/' song.txt

이 출력:

Output
is this the song that never endsit yes, goes on and on, my friendpeople some started singing itknowing not what it wasthey'll and continue singing it foreverbecause... just

이것은 훨씬 더 이상 지난 시간이다., 그러면 구두점이 연결된 단어와 그룹화됩니다.

괄호 안의 표현식을 반복하는 방법에 주목하십시오(*문자없이 한 번,그리고 한 번 함께). 이것은*문자가 0 번 이상 앞에 오는 문자 집합과 일치하기 때문입니다. 즉,와일드 카드와의 일치가 패턴을 찾을 수 없더라도”일치”로 간주됩니다.

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

결론

이 튜토리얼에서는sed명령을 탐색했습니다. 당신은 특정한 인쇄 라인에서 파일을 검색에 대한 텍스트,삭제선,덮어쓴 원본 파일을 사용하는 정규 표현식을 텍스트를 교체합니다. 제대로 구성된 sed 명령을 사용하여 텍스트 문서를 신속하게 변환 할 수있는 방법을 이미 볼 수 있어야합니다.

이 시리즈의 다음 기사에서는 좀 더 고급 기능을 살펴볼 것입니다.피>

답글 남기기

이메일 주소를 발행하지 않을 것입니다. 필수 항목은 *(으)로 표시합니다