Vi search & replace

John Jeong (토론 | 기여)님의 2017년 11월 6일 (월) 21:59 판 (→‎코드)
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)

1 개요[ | ]

VI search & replace
  • 원하는 디렉토리 모든 파일에서 특정 패턴을 새로운 패턴으로 변경
  • 변경 전 각각의 변경 지점에서 변경을 진행할 것인지에 대한 확인을 진행함

2 코드[ | ]

#!/bin/bash
# How to use
# replace.sh pattern new_pattern

#filename
filename=$(basename $0)

#pattern
pattern=$1
new_pattern=$2

#working directory
working_directory=$(pwd)"/"

files=$(find $working_directory -type f -name '*.*' -and ! -name $filename)

for file in $files
do
    vim -c "%s/$pattern/$pattern2/gc" -c "wq" $file
done
→vim -c에서 -c는 커멘드 옵션으로 vim 실행후 그 안에서 실행할 명령을 줄 수 있음
→%s/pattern/new_pattern/gc 에서 끝의 c는 confirmation, 즉 변경 여부를 묻도록 하는 절차를 추가하는 옵션임
→"! -name $0" 조건은 수행 파일인 replace.sh는 실행에서 제외하기 위한 조건임
→코드는 -name *.*로 모든 파일에서 찾도록 되어 있으나 *.c, *.php 등으로 변경하여 특정 파일 포멧에서 찾는 것도 가능함

3 예시[ | ]

3.1 디렉토리 구성[ | ]

  • /test/a/b 구조에 a.txt 파일을 a, b디렉토리에 각각 배치
john@zetawiki:/test$ tree a
a
├── a.txt
└── b
    └── a.txt

1 directory, 2 files

3.2 파일 내용 변경[ | ]

  • test 디렉토리의 모든 파일의 모든 숫자 111을 aaa로 변경
john@zetawiki:/test$ ./replace.sh 111 aaa

4 같이 보기[ | ]

5 참고[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}