I know grep can be use to do partial search, for example if i use
echo "Enter example"
read example
echo "Enter Subject"
read subject
grep -i ^$example info.txt | grep -i ^[^,]*:$subject
The output will be all the lines of string that has, let's say i key in "example", it will display all the lines of string that has the string "example".
I need this function so that the user can do a general search on what are the list of available reading materials there are in the info.txt.
I am currently using if statements, if both $example and $subject have information in it, it will do specific search, like literally string matching string, else it will return false.
Is there anyway to make the search more flexible, or to let it search specifically, like there are many examples in the info.txt.
- Example 1:Basic mathematics
- Example 2:Advance mathematics
- Example 3:How to create a good example ?
So if i key in "example" and "mathematics", it will return false. However, if i key in "example 1" and "basic mathematics", it will echo out the output. I asked around, most of my friends recommended me to use awk, but if i do that , i will have to redo my whole script as I'm using grep in most function to do searches.
My teacher only taught us grep at that point of time, therefore, only understand basic grep and did not know about awk.
sed
. But I think it should work anyway, you just have to be careful not to restrict your regular expression too much. grep doesn't do exact matching unless you force it to (for instance, by searching '^example:' instead of just 'example[^:]*:'. And be careful, you should quote "$example" and "$subject" otherwise spaces will result in unexpected behaviour. – orion Jan 13 '15 at 14:59grep -i "^$example.*:.*$subject" info.txt
– Costas Jan 13 '15 at 15:03