1 |
On 18/08/2014 12:29, Stroller wrote: |
2 |
> |
3 |
> On Mon, 18 August 2014, at 10:42 am, wraeth <wraeth@×××××××××.au> wrote: |
4 |
> |
5 |
>> On Mon, 2014-08-18 at 18:54 +1000, Adam Carter wrote: |
6 |
>>> But this matches if grep fails both times as well as when it matches both |
7 |
>>> time. Any ideas? |
8 |
>> |
9 |
>> If you don't mind using a quick loop, you could use something like: |
10 |
>> |
11 |
>> n=0 |
12 |
>> for f in file1.txt file2.txt file3.txt file4.txt; do |
13 |
>> grep 'string' ${f} >> /dev/null && n=$[n+1] |
14 |
>> done |
15 |
>> |
16 |
>> if [[ $n == 4 ]]; then |
17 |
>> do_something |
18 |
>> fi |
19 |
> |
20 |
> I've solved similar problems the same way myself, but I hope you'll forgive me for offering unsolicited critique on a small detail. |
21 |
> |
22 |
> In the above 4 is a constant, and thus it's independent of the number of files being tested. |
23 |
> |
24 |
> I propose addressing this with an array of the filenames. |
25 |
> |
26 |
> Thus additional files can be added for testing, without manual adjustment of the expected total. |
27 |
> |
28 |
> files=("file1.txt" "file2.txt" "file3.txt" "file4.txt") |
29 |
> n=0 |
30 |
> for f in ${files[@]}; do |
31 |
> grep 'string' ${f} >> /dev/null && n=$[n+1] |
32 |
|
33 |
I would write `grep -q -m1 -F 'string' ...` here. In particular, -m1 |
34 |
will short-circuit after finding one match. |
35 |
|
36 |
> done |
37 |
> |
38 |
> if [[ $n == ${#files[@]} ]]; then |
39 |
> do_something |
40 |
> fi |
41 |
> |
42 |
> Bash array syntax is a bit arcane, but at least these very useful data structures are available. |
43 |
|
44 |
Here's a slightly different take. It avoids multiple grep invocations, |
45 |
which could be a good thing in the case of a lengthy file list. |
46 |
|
47 |
files=(file1.txt file2.txt file3.txt file4.txt) |
48 |
string="matchme" # Using -F below as it's a string, not a regex |
49 |
|
50 |
count=0 |
51 |
while read -r matches; do |
52 |
(( count += matches )) |
53 |
done < <(grep -hcm1 -F "$string" ${files[*]}) |
54 |
|
55 |
if (( count == ${#files[@]} )); then |
56 |
do_something |
57 |
fi |
58 |
|
59 |
--Kerin |