2013-02-14 3 views
16

나는 grep 명령에 문제가 있습니다.여러 파일에서 grep 검색의 마지막 줄 가져 오기

find . -name "FILE_NAME" | xargs -I name grep PATERN name 

: 나는 여러 선택한 파일에 그렙 검색을 할 수있는 방법을 찾아

grep PATERN FILE_NAME | tail -1 

:

나는 단지 그렙 검색의 마지막 줄을 표시하는 방법을 발견했습니다 이제 각 단일 파일에 대한 grep 결과의 마지막 줄만 가져 오려고합니다.

find . -name "FILE_NAME" | xargs -I name grep PATERN name | tail -1 

이 나에게 나는 모든 파일의 마지막 일치 된 patern을하고 싶은 마지막 파일의 마지막 값을 반환합니다 : 이 시도.

답변

25
for f in $(find . -name "FILE_NAME"); do grep PATERN $f | tail -1; done 
+0

위대한 작품! 고맙습니다! : D –

+0

유감스럽게도 전체 파일을 검색하고 마지막 결과 만 반환하면 대용량 파일이나 복잡한 패턴 검색에 효율적이지 않습니까? 당신의 for 루프에서 다음과 같은 것은 어떨까요? 'tac file | grep -m1 -oP '(? <=tag>). * (?=) '| head -n 1 ' 또는 심지어 grep -m1 -oP (? <=tag>)'(tac 파일) '<< (tac 파일) – kisna

2

어떻게 당신이 너무 명령을 실행할 찾을 수 있습니다

find . -name "FILE_NAME" -print0 | while read -d '' aa 
do 
    grep PATTERN "$aa" | tail -1 
done 
+0

첫 번째 의견과 같은 정신이 완벽하게 작동합니다! –

0

이 좋은 선생님에 대한 :

find . -name "<file-name-to-find>" -exec grep "<pattern-to-match>" "{}" ";" | tail -1 

"{}"에 기록 할 때 쉘 globing 및 expasion로 알아서, 파일 이름입니다 명령

-1

루프가 필요없는 솔루션이 있으므로 OP가 원하는 것을 제공합니다. tail -1없이 비교

find . -type f -exec sh -c "fgrep print {} /dev/null |tail -1" \; 

./tway.pl:print map(lambda x : x[1], filter(lambda x : x[0].startswith('volume'), globals().items())) 
./txml.py:   print("%s does not exist: %s\n" % (host, error)) 
./utils.py:print combine_dicts(a, b, operator.mul) 
./xml_example.py:print ET.tostring(root, method="text") 

너무 많은 라인 파일 당을 제공하지만, 위의 작품 증명한다.

find . -type f -exec sh -c "fgrep print {} /dev/null" \; 

을 제공합니다

./tway.pl:print map(lambda x : x[1], filter(lambda x : x[0].startswith('volume'), globals().items())) 
./txml.py:   print("%s resolved to --> %s\n" % (host, ip)) 
./txml.py:   print("%s does not exist: %s\n" % (host, error)) 
./utils.py:print "a", a 
./utils.py:print "b", b 
./utils.py:print combine_dicts(a, b, operator.mul) 
./xml_example.py: print ">>" 
./xml_example.py: print ET.tostring(e, method="text") 
./xml_example.py: print "<<" 
./xml_example.py:print ET.tostring(root, method="text") 

편집-는/dev/당신은 파일 이름을 원하지 않는 경우는 null이 출력에 포함 제거합니다.

-2

이 작업을 수행하는 가장 빠른 방법은 파일의 마지막 1 (또는 그 이상) 줄을 얻은 다음 grep을 사용하는 것입니다. 그래서 -

tail -1 filenames.* | grep "what you want to grep for" 
+2

마지막 줄이 반드시 패턴과 일치하지는 않으므로 그렇지 않습니다. 파일 당 마지막 일치 항목을 표시합니다. –

-1

마지막 라인을 찾을 수있는 또 다른 방법은 파일을 출력 일치를 반대하는 것입니다.

find . -name "FILE_NAME" | xargs -I name sh -c 'tac name|sed -n "/PATTERN/{p;q}"' 
0

grep의 -B (before) 매개 변수로 시작할 수 있습니다. 예를 들어, 경기 전 5 행을 얻으려면 :

[email protected] /etc/php5/apache2 $ grep -i -B5 timezone php.ini 
[CLI Server] 
; Whether the CLI web server uses ANSI color coding in its terminal output. 
cli_server.color = On 

[Date] 
; Defines the default timezone used by the date functions 
; http://php.net/date.timezone 
;date.timezone = 
관련 문제