我想編譯一個簡單的bash腳本。它應該搜索名稱與提供的模式相匹配的文件(模式作爲參數提供)並列出文件的第幾行。所有文件將在一個目錄中。Bash腳本 - 搜索名稱與模式匹配的文件
我知道我應該使用head -n 3
列出文件的前幾行,但我不知道如何搜索提供的模式以及如何將它們放在一起。
非常感謝您所有的答案。
我想編譯一個簡單的bash腳本。它應該搜索名稱與提供的模式相匹配的文件(模式作爲參數提供)並列出文件的第幾行。所有文件將在一個目錄中。Bash腳本 - 搜索名稱與模式匹配的文件
我知道我應該使用head -n 3
列出文件的前幾行,但我不知道如何搜索提供的模式以及如何將它們放在一起。
非常感謝您所有的答案。
find . -type f -name 'mypattern*.txt' -exec head -n 3 {} \;
的-exec
之前添加-maxdepth 0
如果你不希望下降到子目錄。
無需真的,外殼會爲你做的模式:
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
Bash有一個globstar
選項,在設置時將使您能夠使用**
搜索子目錄:
head -3 **/mypattern*.txt
要設置globstar,您可以添加follow ing到您的.bashrc:
shopt -s globstar
您可以使用'\ +'而不是'\;'作爲終止符。這將爲'exec'命令提供多個文件。 – RedX