2013-12-10 195 views
0

我想編譯一個簡單的bash腳本。它應該搜索名稱與提供的模式相匹配的文件(模式作爲參數提供)並列出文件的第幾行。所有文件將在一個目錄中。Bash腳本 - 搜索名稱與模式匹配的文件

我知道我應該使用head -n 3列出文件的前幾行,但我不知道如何搜索提供的模式以及如何將它們放在一起。

非常感謝您所有的答案。

回答

1
find . -type f -name 'mypattern*.txt' -exec head -n 3 {} \; 

-exec之前添加-maxdepth 0如果你不希望下降到子目錄。

+1

您可以使用'\ +'而不是'\;'作爲終止符。這將爲'exec'命令提供多個文件。 – RedX

2

無需真的,外殼會爲你做的模式:

head -3 *.c 
==> it.c <== 
#include<stdio.h> 
int main() 
{ 

==> sem.c <== 
#include <stdio.h>   /* printf()     */ 
#include <stdlib.h>   /* exit(), malloc(), free() */ 
#include <sys/types.h>  /* key_t, sem_t, pid_t  */ 

==> usbtest.c <== 

又如:

head -3 file[0-9] 
==> file1 <== 
file1 line 1 
file1 line 2 
file1 line 3 

==> file2 <== 
file2 line 1 
file2 line 2 
file2 line 3 

==> file9 <== 
file9 line 1 
file9 line 2 
file9 line 3 
2

Bash有一個globstar選項,在設置時將使您能夠使用**搜索子目錄:

head -3 **/mypattern*.txt 

要設置globstar,您可以添加follow ing到您的.bashrc:

shopt -s globstar 
+0

'**'在大多數shell中與'*'完全相同。你在研究哪個外殼? – Alfe

+0

我正在使用bash。從bash手冊頁:*匹配任何字符串,包括空字符串。當啓用globstar shell選項並在路徑名擴展上下文中使用*時,用作單個模式的兩個相鄰*將匹配所有文件以及零個或多個目錄和子目錄。如果後面跟着一個/,兩個相鄰的*只會匹配目錄和子目錄。 – cforbish

+0

啊,好的。該shell選項默認是關閉的;也許你應該添加這方面的答案(如何切換等),比它成爲一個值得的:) – Alfe

相關問題