samedi 3 juin 2017

How to iterate word by word in array in bash

i have a simple script, where i make search of words from file

words="you are hogan"

for i in $words; do
if grep -q "$i" text.txt; then
        echo "word(s) are exists"
        grep "$i" text.txt
else
        echo "word(s) are not exists"
fi
done

it works, i can make grep word by word. My script is is the same:

grep "you" text.txt
grep "are" text.txt
grep "hogan" text.txt 

but, the i received another task. i want to search and replace word by word text. so, i should create second variable, with words, what i should use instead words from first variable $words. how i understand, that i should in one loop use two variables. i know, that i can use array in this case. ok, let's do it, i tries to make grep, like first example:

words="you are hogan"
words2="wwe wwf nukem"

for ((i=0;i<${#words[@]};++i)); do
if grep -q "${words[i]}" text.txt; then
        echo "word(s) are exists"
        echo "${words[i]}"
else
        echo "word(s) are not exists"
fi
done

result is not good.

+ (( i=0 ))
+ (( i<1 ))
+ grep -q 'you are hogan' text.txt
+ echo 'word(s) are not exists'
word(s) are not exists

How you can see, it tries to make grep of all phraza, not for each word. how can i do grep command for each word, like first example ?

Aucun commentaire:

Enregistrer un commentaire