ksh - search for multiple strings and write lines to file

670 views Asked by At

Any help would be greatly appreciated. I can read code and figure it out, but I have trouble writing from scratch.

I need help starting a ksh script that would search a file for multiple strings and write each line containing one of those strings to an output file.

If I use the following command:

$ grep "search pattern" file >> output file

...that does what I want it to. But I need to search multiple strings, and write the output in the order listed in the file.

Again... any help would be great! Thank you in advance!

3

There are 3 answers

0
Walter A On

Sometimes you need egrep.

egrep "first substring|second substring" file

When you have a lot substrings you can put them in a variable first

findalot="first substring|second substring"
findalot="${findalot}|third substring"
findalot="${findalot}|find me too"
skipsome="notme"
skipsome="${skipsome}|dirty words"
egrep "${findalot}" file | egrep -v "${skipsome}"
0
Ajay On

Use "-f" in grep . Write all the strings you want to match in a file ( lets say pattern_file , the list of strings should be one per line) and use grep like below

grep -f pattern_file file > output_file 
0
jcoppens On

Have a look at the regular expression manuals. You can specify multiple strings in the search expression such as grep "John|Bill"

Man grep will teach you a lot about regular expressions, but there are several online sites where you try them out, such as regex101 and (more colorful) regexr.