Reputation: 17
I am trying to compile a simple bash script. It should search for files whose name matches a supplied pattern (pattern is supplied as an argument) and list a few first lines of the file. All the files will be in one directory.
I know I should use head -n 3
for listing the first few lines of the file, but I have no idea how to search for that supplied pattern and how to put it together.
Thank you very much for all the answers.
Upvotes: 0
Views: 241
Reputation: 8829
Bash has a globstar
option that when set will enable you to use **
to search subdirectories:
head -3 **/mypattern*.txt
To set globstar you can add the following to your .bashrc:
shopt -s globstar
Upvotes: 2
Reputation: 208052
No need really, the shell will do patterns for you:
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 <==
Another example:
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
Upvotes: 2
Reputation: 59596
find . -type f -name 'mypattern*.txt' -exec head -n 3 {} \;
Add a -maxdepth 0
before the -exec
if you do not want to descend into subdirectories.
Upvotes: 1