linux - shell script to find a word in a list of files, all of them given as parameters -


i need simple shell program has this:

script.sh word_to_find file1 file2 file3 .... filen 

which display

word_to_find 3 - if word_to_find appears in 3 files 

or

word_to_find 5 - if word_to_find appears in 5 files  

this i've tried

#!/bin/bash  count=0 in $@;   if [ grep '$1' $i ];then      ((count++))   fi done echo "$1 $count" 

but message appears:

syntax error: "then" unexpected (expecting "done"). 

before error was

[: grep: unexpected operator. 

try this:

#!/bin/sh printf '%s %d\n' "$1" $(grep -hm1 "$@" | wc -l) 

notice how script's arguments passed verbatim grep -- first search expression, rest filenames.

the output grep -hm1 list of matches, 1 per file match, , wc -l counts them.

i posted answer grep -l require filenames never contain newline, rather pesky limitation.

maybe add -f option if regular expression search not desired (i.e. search literal text).


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -