기본 콘텐츠로 건너뛰기

[리눅스] 파일 내 문자열 검색

출처: http://soharang.tistory.com/815 [e-Story]

Linux에서 파일 내에 특정 문자열을 검색해야 하는 경우가 종종 있다.


- 현재 디렉토리 내 확장자가 txt인 파일들을 중에서 "홍길동"이라는 문자열을 갖고 있는 파일의 한 줄과 이름을 보여준다.
find . -name "*.txt" | xargs grep 홍길동

- 이 때 검색어로 사용된 문자열은 색을 달리하여 표시하고 싶다면
find . -name "*.txt" | xargs grep --color=auto 홍길동

 - 검색어의 위치(줄번호)를 같이 표기하고 싶다면
find . -name "*.txt" | xargs grep -n 홍길동

- 대소문자를 구분하고 싶지 않다면
find . -name "*.txt" | xargs grep -i LgMobile
즉, LGMobile, LGMOBILE, lgMobile을 가리지 않고 찾는다.

- 현재 디렉토리 내 확장자가 txt인 파일들을 중에서 "홍길동"이라는 문자열을 갖고 있는 파일의 이름만 보고 싶다면
find . -name "*.txt" | xargs grep -l 홍길동

- 검색 결과에 다음과 같은 메시지가 포함된다면
grep: [특정경로]: No such file or directory

2>/dev/null 을 추가하면 해당 메시지를 표시하지 않고 찾은 결과만 볼 수 있다. 즉,
find . | xargs grep 2>/dev/null 홍길동

- 모든 옵션은 함께 사용 가능하다.
find . -name "*.txt" | xargs grep --color=auto -n 2>/dev/null 홍길동

※출처 : [리눅스나라]
[unix.com


댓글

이 블로그의 인기 게시물

dmesg 메시지 실시간으로 보기

참조사이트 http://imitator.kr/Linux/556 # tail -f /var/log/messages # tail -f |dmesg //기본 2초 단위로 갱신 된다. # watch "dmesg | tail -f" //1초 단위로 갱신하면서 보여준다. # watch -n 1 "dmesg | tail -f" // 보여주는 줄을 20으로 늘린다. (기본 10줄) # watch -n 1 "dmesg | tail -f -n 20"

java 특정 디렉토리에 있는 파일 목록을 읽어내기, 정렬해서 가져오기

폴더 리스트 가져오기 String path="C:\"; File dirFile=new File(path); File []fileList=dirFile.listFiles(); for(File tempFile : fileList) {   if(tempFile.isFile()) {     String tempPath=tempFile.getParent();     String tempFileName=tempFile.getName();     System.out.println("Path="+tempPath);     System.out.println("FileName="+tempFileName);     /*** Do something withd tempPath and temp FileName ^^; ***/   } } 정렬해서 가져오기 import java.io.FileFilter; import java.io.IOException; import java.util.Arrays; import java.util.Date; import org.apache.commons.io.comparator.LastModifiedFileComparator; import org.apache.commons.io.filefilter.FileFileFilter; public class LastModifiedFileComparatorTest { public static void main(String[] args) throws IOException { File directory = new File("."); // get just files, not directories File[] files = directory.listFiles((FileFilter) FileFileFilter.FILE); System.out.println("Defaul...