[Linux]예제로 알아보는 sed 명령어 사용법

사실은 Linux 초기 setting할 때를 제외하고 파일 시스템에서 텍스트 파일을 생성/변경/삭제할 일이 거의 업습니다. 가끔 로그 파일을 살펴볼 때나 명령어를 사용하는 정도지요. 그러다 보니 텍스트 파일에서 문자를 찾거나 편집하거나 삭제할 때마다 명령어 사용법을 찾아보고 있습니다. 이 번 블로그는 제가 제일 자주 사용하는 텍스트 파일 관련 명령어들 중에 sed 사용법을 예제를 통해 알아보겠습니다. 정규표현식과 함께 사용하면 더욱 강력한 기능으로 사용할 수 있습니다.

Stream Editor의 약자로, Linux와 유닉스 시스템에서 텍스트 데이터를 처리하고 변환하는 명령어입니다. 주로 텍스트 파일 내에서 패턴을 찾아 원하는 형태로 변경하거나 삭제하는데 사용됩니다.

일반적인 구문:

sed [options] [script] [file | text]

 
기본 옵션(options):

  • -i: 원본 파일을 직접 수정합니다.
  • -e: 여러 개의 sed 명령어를 사용할 때 적용합니다.
  • -n: 출력을 기본 동작에서 비활성화하고, 명령어에 의해 특정 라인만 출력하도록 합니다.

주요 명령어(scripts):

  • /검색어/: 지정된 검색어가 포함된 라인을 대상으로 작동
  • /검색어/!: 지정된 검색어가 포함되지 않은 라인을 대상으로 작동
  • s: 패턴을 찾아 해당 패턴을 원하는 문자열로 대체합니다.(substitute)
  • d: 해당 라인을 삭제합니다.(delete)
  • ,+숫자d: 해당 라인과 함께 지정된 숫자 만큼의 다음 라인들을 추가 삭제합니다.
  • p: 선택된 라인을 출력합니다.(print)
  • i: 선택된 라인 앞에 새로운 텍스트를 삽입합니다.(insert)
  • a: 선택된 라인 뒤에 새로운 텍스트를 삽입합니다.(append)

 

  1. 기본적인 텍스트 변환
    – ‘lines’ 옵션 : 지정한 라인들을 대상으로 변환 (숫자 / 숫자,숫자 / 숫자,$ / $)
    – ‘g’ 옵션 : 생략하면 첫 번째만, ‘g’는 전체, ‘숫자’는 해당 n번째 , ‘g숫자’는 해당 n번째 이후 모두 “new” 텍스트로 변환
    – ‘i’ 옵션 : 대소문자를 구분하지 않습니다.

    sed '[lines] s/old/new/[i][g]' file

    # echo -e "unix unix unix\nunix unix unix\nunix unix unix" | sed '1 s/unix/Linux/' Linux unix unix unix unix unix unix unix unix # echo -e "unix unix unix\nunix unix unix\nunix unix unix" | sed '1,2 s/unix/Linux/' Linux unix unix Linux unix unix unix unix unix # echo -e "unix unix unix\nunix unix unix\nunix unix unix" | sed '2,$ s/unix/Linux/' unix unix unix Linux unix unix Linux unix unix # echo -e "unix unix unix\nunix unix unix\nunix unix unix" | sed '$ s/unix/Linux/' unix unix unix unix unix unix Linux unix unix # echo -e "unix unix unix\nunix unix unix\nunix unix unix" | sed 's/unix/Linux/' Linux unix unix Linux unix unix Linux unix unix # echo -e "unix unix unix\nunix unix unix\nunix unix unix" | sed 's/unix/Linux/2' unix Linux unix unix Linux unix unix Linux unix # echo -e "unix unix unix\nunix unix unix\nunix unix unix" | sed 's/unix/Linux/g' Linux Linux Linux Linux Linux Linux Linux Linux Linux # echo -e "unix unix unix\nunix unix unix\nunix unix unix" | sed 's/unix/Linux/g2' unix Linux Linux unix Linux Linux unix Linux Linux
  2. 모든 라인의 마지막으로 일치하는 텍스트만 변환
    sed 's/\(.*\)old/\1new/' file

    # echo -e "unix unix unix os\nunix unix unix os\nunix unix unix os" | sed 's/\(.*\)unix/\1Linux/' unix unix Linux os unix unix Linux os unix unix Linux os
  3. 지정된 검색어가 포함된 라인만 텍스트 변환
    sed '/검색어/ s/old/new/' file

    # echo -e "unix - feature\nLinux - feature\nWindows - feature" | sed -e '/unix/ s/feature/expensive/; /Linux/ s/feature/opensource/' unix - expensive Linux - opensource Windows - feature
  4. 지정된 검색어가 포함되지 않은 라인만 텍스트 변환
    sed '/검색어/! s/old/new/' file

    # echo -e "unix - feature\nLinux - feature\nWindows - feature" | sed '/Windows/! s/feature/shell commands/' unix - shell commands Linux - shell commands Windows - feature
  5. 매칭되는 텍스트 전/후로 지정한 문자 추가
    sed 's/\(string\)/[add_before]\1[add_after]/' file

    # echo "Linux is a opensource." | sed 's/\(opensource\)/powerful \1 OS/' Linux is a powerful opensource OS.
  6. slash(/) 문자 앞에 backslash(\) 표시
    sed 's/$/\n/g' file

    # echo "/etc/sysconfig/network-scripts/ifcfg-eth0" | sed 's;/;\\/;g' \/etc\/sysconfig\/network-scripts\/ifcfg-eth0
  7. 기본적인 라인 삭제
    – /text/d : 매칭되는 텍스트가 있는 라인 삭제
    – /text/Id : 대소문자에 상관없이 매칭되는 텍스트가 있는 라인 삭제
    – /text/!d : 매칭되는 텍스트가 없는 라인 삭제

    sed '/text/[d | Id | !d]' file

    # # echo -e "unix\nLinux\nWindows" | sed '/Windows/d' unix Linux # echo -e "unix\nLinux\nWindows" | sed '/unix/!d' unix
  8. 텍스트 라인의 끝에 있는 공백 문자 제거
    sed 's/[[:blank:]]*$//' file

    # echo -e "Linux \t" | sed 's/[[:blank:]]*$//' Linux
  9. 매칭되는 텍스트의 다음에서 줄바꿈하고 지정한 텍스트로 시작하는 새로운 라인 추가
    sed 's/text1/&\ntext2/' file

    # echo -e "unix\nWindows" | sed 's/unix/&\nLinux/' unix Linux Windows
  10. 아래로 리스트되어 있는 문자열을 “,”로 구분하기
    sed -z 's/\n/,/g' file

    # echo -e "unix\nLinux\nWindows" | sed -z 's/\n/,/g' | sed 's/\(.*\),/\1\n/' unix,Linux,Windows
  11. 매칭되는 텍스트를 대문자 또는 소문자로 변환
    – ‘s/\(text\)/\L\1/Ig’ : 소문자로 변환
    – ‘s/\(text\)/\U\1/Ig’ : 대문자로 변환

    sed 's/\(text\)/[\L|\U]\1/Ig' file

    # echo -e "unix\nLinux\nWindows" | sed 's/\(unix\)/\U\1/Ig' UNIX Linux Windows # echo -e "unix\nLinux\nWindows" | sed 's/\(Linux\)/\L\1/Ig' unix linux Windows # echo -e "unix\nLinux\nWindows" | sed 's/\(.*\)/\L\1/Ig' unix linux windows # echo -e "unix\nLinux\nWindows" | sed 's/\(.*\)/\U\1/Ig' UNIX LINUX WINDOWS
  12. 줄마다 빈 줄 삽입
    sed 's/$/\n/g' file

    # echo -e "unix unix unix os\nunix unix unix os\nunix unix unix os" | sed 's/$/\n/g' unix unix unix os unix unix unix os unix unix unix os
  13. 파일경로에서 path를 삭제하고 파일명만 출력(= basename)
    sed 's/.*\///' file_path

    # echo "/etc/sysconfig/network-scripts/ifcfg-eth0" | sed 's/.*\///' ifcfg-eth0
  14. 숫자 앞에 화폐 기호 추가하기
    sed 's/\([0-9]\)/$\1/' file_path

    # echo -e "unix\t100\nLinux\t200\nWindows\t300" | sed 's/\([0-9]\)/$\1/' unix $100 Linux $200 Windows $300

 
아래는 특정 파일들에 포함된 텍스트를 변환(OLD > NEW)하는 스크립트입니다. 테스트 서버를 구축할 때 아래 스크립트를 사용해서 환경설정 파일이나 소스 코드를 수정하고 있습니다.

#!/bin/bash

OLD="before_text"
NEW="after_text"

FILES[0]="/path/file1"
FILES[1]="/path/file2"

for file in "${FILES[@]}" ; do
  if [ -f ${file} ]; then
    if [ -w ${file} ]; then
      echo "sed -i 's/${OLD}/${NEW}/g' ${file}"
#      sed -i 's/${OLD}/${NEW}/g' ${file}
    else
      echo "Please check the permissions and attributes of the file(${file}) using ls and lsattr."
  else
    echo "The file(${file}) does not exist."
  fi
done

You may also like...

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다