我想编译一个简单的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