목록화된 특정 단어들을 특정디렉토리에서 모두 검색하려고 만들어봤다.
예를 들자면 "뭉충닷컴" 텍스트가 들어간 파일들을 특정디렉토리에서 찾는 방법은 간단하다
리눅스상에서 find명령어를 사용하든 편집기에서 찾기를 이용하면된다.
헌데 찾고자 하는 텍스트가 "뭉충닷컴", "네이버", "다음", "네이트" ....등등 이렇게 많아질때는 곤란하다
작업하다보니 이런 일이 생겨서(아주 드물지만 -_-) 간단하게 쉘 스크립트 만들었다.
#!/bin/bash
export file=$1
export logfile="$1.result.txt"
#파라미터값이 없을경우
if [ -z $1 ] || [ -z $2 ]; then
echo "검색어목록이 입력된 파일명을 파라미터로 넣어주세요"
echo "ex) search_content.sh 파일명 검색경로"
exit
fi
# 검색어 파일이 없을경우
if ! [ -f $file ]; then
echo "$1 파일이 없습니다."
exit
fi
# 결과파일이 있을 경우 삭제 처리 함
if test -e $logfile
then
rm $logfile
fi
cat $file | \
while read line
do
echo "$line"
find $2 -type f | xargs grep -il $line > "search_result_temp.txt"
cat search_result_temp.txt | \
while read line_temp
do
echo "$line,$line_temp" >> $logfile
done
rm search_result_temp.txt
done
파일 이름은 "search_content.sh"로 했다.
이렇게 shell 파일 만들고 난 후 사용방법은 다음과 같다.
아래 내용이 포함된 wordlist.txt 파일을 만든다.
뭉충닷컴
네이버
다음
네이트
그런 후 리눅스 상에서 아래와 같이 명령어 입력하면 된다.
search_content.sh wordlist.txt /home/hosting/web/
search_content.sh "단어목록파일" "찾고자하는경로"
이렇게 하면 찾고자하는 경로 하위디렉토라까지 파일가지 모두 뒤져서 보여주고 결과 파일은
wordlist.txt.result.txt 파일로 내보낸다.
이 파일 열어보면 아래와 같이 왼편엔 찾고자하는 단어 오른편엔 찾은 파일경로가 나타난다.
뭉충닷컴,/home/hosting/web/aaaa.txt
뭉충닷컴,/home/hosting/web/bbb/cc.txt
뭉충닷컴,/home/hosting/web/test.txt
네이버,/home/hosting/web/kaka/oo/toto/aaaa.txt
네이트,/home/hosting/web/nate/aaa.txt

위 예제는 특정단어가 포함되는 것을 찾는것인데
만약, 전체단어 일치로해서 파일내용 검색을 하고 싶다면
아래와 같이 w 옵션을 주면 된다.
find $2 -type f | xargs grep -iwl $line > "search_result_temp.txt"