I am trying to write a shell script that will search for a regular expression in each of the files in the current directory without using temp files.
Originally, I did this using a temp file to store echo * | sed 's/ /\n/g' and then looped through each line of this file, using cat on each and then grepping my expression and counting the lines of output. I was having some trouble with temp files being searched and was wondering if I could do everything using variables or some non-temp-files method (I don’t really want to create a separate directory for the temp files either).
The problem I was having with variables was that after I had set the value of the variable to the output of echo * | sed 's/ /\n/g', I didn’t know how to loop through each line so I could get the expression count from the files.
I just want the following to work (where I hardcode the expression):
% ls
% file1 file2 file3
% ./countMost.sh
% file2(28)
% ls
% file1 file2 file3
signifying that file2 has the most instances of the expression (28 of them).
You can try something like this:
Where
regexis your regular expression (can useegrepas well) and thefilesare your list of files.Given 3 files:
and I run:
I get the output:
Additionally, adding the
| head -n 1at the end only gives me: