2013-02-14 507 views
16

我curently有一些問題與grep命令。得到grep查找最後一行的多個文件

我發現只顯示grep搜尋的最後一行的方式:

grep PATERN FILE_NAME | tail -1 

我也覺得要在多個選定的文件grep搜尋方式:

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

現在我只想得到每個單個文件的grep結果的最後一行。 我嘗試這樣做:

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

這將返回我只有最後一個文件,我想有每個文件的最後一個匹配的百通的最後一個值。

回答

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

很好用!謝謝! :d – 2013-02-15 12:48:15

+0

不幸的是,這不會是有效的大型文件或複雜的模式搜索,如果你正在尋找整個文件並返回剛剛過去的結果?如何像下面這樣,在你的for循環: 'TAC文件| grep的-M1 -OP「(?<=tag>)。*(?=)'| head -n 1' 或甚至 'grep -m1 -oP'(?<=tag>)。*(?=)'<<(tac文件)' – kisna 2015-08-02 14:43:10

2

這個怎麼樣好先生

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

與第一條評論相同的精神,完美的作品! – 2013-02-15 12:49:35

0

您可以使用找到過執行命令:

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

「{}」是文件名,書寫時採取與外殼globing和expasion護理命令

-1

有沒有需要循環的解決方案,這給出了OP所需要的。

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") 

沒有tail -1相比給人太多行每個文件,但證明上述作品。

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

最後一行不一定匹配模式,所以這不會顯示每個文件的最後一場比賽。 – 2015-04-23 07:40:10

-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 = 
相關問題