Your regex-building command is a little bit wrong; besides, it's very inefficient to rebuild the same pattern on every loop iteration.
Although bash has a read
command it's generally discouraged to use it for processing large amounts of text, since it's very slow, as well as being a common source of scripting errors. So try to restrict the use of read
to processing simple user input.
As others have mentioned, this is a job for grep
. Or if you want more control, consider using awk, which has good regex abilities. But if you really want to do it in a way similar to your posted code, here's one way to do it.
#!/usr/bin/env bash
pat='^('$(paste -sd'|' champs.txt)')$'
printf "pattern: '%s'\n" "$pat"
IFS=
tr -s '[:blank:]' '\n' < t.txt |
while read -r word; do
if [[ "$word" =~ $pat ]];
then echo "'$word' in list"
else echo "'$word' NOT in list"
fi
done
(The above script passes ShellCheck analysis).
As you can see, we build the regex pattern pat
outside the loop; I've added a printf
to display the pattern so we can be sure it's what we want. Note that it's generally much better to use printf
than echo
to display arbitrary strings.
I've modified your t.txt
to add a few extra test words, but used the same champs.txt
as posted above.
t.txt
select * from student;
insert name, age, from professors;
delete from departement where DPTNUM= '20';
test number ins settle deleted
And here's the output:
pattern: '^(select|insert|into|values|delete|drop|from|create|table|where|set|varchar|number)$'
'select' in list
'*' NOT in list
'from' in list
'student;' NOT in list
'insert' in list
'name,' NOT in list
'age,' NOT in list
'from' in list
'professors;' NOT in list
'delete' in list
'from' in list
'departement' NOT in list
'where' in list
'DPTNUM=' NOT in list
''20';' NOT in list
'test' NOT in list
'number' in list
'ins' NOT in list
'settle' NOT in list
'deleted' NOT in list
grep
, but I would like to see an example of the contents oft.txt
andchamps.txt
. – jcbermu Apr 13 '15 at 10:15