BubbleSort
BubbleSort

Reputation: 41

Shell Scripting : Good idea, wrote it bad

I have to make a shell script that returns a list with all files that have word 'hello' on 3 or more lines.

I know the idea, but I think I wrote my script bad.

nr=$(ls | wc -l )

for ((i = 0; i < nr ; i++));do

    fis[$i]=$(ls | sed -n '$i p')

done

for ((i = 0; i < nr ; i++));do

    if [$(cat $(fis[$i]) | grep 'hello' | wc -l) -gt 2 ];

    then

        echo $( fis[$i])

    fi

done

First I take a number "nr" that returns number of files, than a for from 0 to nr and put in an array fis[i] all the files, selecting each line with sed. And than, if fis[i] contains 'hello' on at least 3 lines, I display it.

Upvotes: 1

Views: 42

Answers (1)

anubhava
anubhava

Reputation: 785256

You wrote too much code I think.

You can use this for loop:

files=()
for f in *; do
   [[ $(grep -c "hello" "$f") -gt 2 ]] && files+=("$f")
done

printf "List of files with more than 2 occurrences of 'hello' is:\n"
printf "%s\n" "${files[@]}"

Upvotes: 1

Related Questions