I have several grep filters that I usually use to parse specific information.1st grep:grep pattern1\|pattern2\|pattern3\| file.txt2nd grep: grep patternA\|patternB\|patternC\| file.txtetc.I apply each grep usually to the same file.txtto get an independent output.I would like to know how I can group this bunch of greps into a single bash script in order to get independent outputs based on each type of grep.For example: input file.txt looks as follows:This line1 is the first line in here1This line2 is the second line in here2This line3 is the third line in here3This line4 is the fourth line in here4I usually apply separate greps here to get specific patterns.grep -h -r --color=always line1\|here1 file.txt >>pattern1.txtor grep -h -r --color=always line2\|here2 file.txt >>pattern2.txtThis will highlight only the information required and will give me separate pattern*.txt files to work on. The objective here is to run all these greps in a single time to evaluate the same file and print in shell as follows:Pattern1Pattern2Pattern3etc.Each grep should evaluate the complete file independently.
Execute independent greps in a single shell script
bash;shell script;grep
If I understand the question correctly,its about how to do the same command (grep),with the same options and the same input,but multiple times,with different regex arguments and different outputs.And I guess you want to avoid unnecessary repetition/duplication.It seems like you want an array of regular expressions (search strings):declare -A regexregex[1]=line1\|here1regex[2]=line2\|here2regex[3]=line3\|here3regex[4]=line4\|here4for i in ${!regex[@]}do        grep -h -r --color=always ${regex[$i]} file.txt >> pattern$i.txtdoneThe first line (declare -A regex) declares an associative arraycalled regex; that means it creates the array as a placeholder,but doesn't enter any information (elements) into it.The next four lines populate the array with four elements,which are the regular expressions,indexed by the numbers 1, 2, 3, and 4.(Im using those indices because thats what you seem to want,butyou can use any distinct strings as indices:for example, uno, dos, tres and cuatro,or ant, bat, cat and dog.†)The for statement, fori in${!regex[@]},causes the variable i to iterate throughthe index values 1, 2, 3, and 4.(If I had left out the ! and said fori in${regex[@]},it would have iterated through the element values,line1\|here1, line2\|here2, line3\|here3 and line4\|here4.)When $i is 1, ${regex[$i]} reduces to ${regex[1]},which expands to line1\|here1.So, the loop iterates (executes) four times,executing the four grep commands that you want.If you want to run the grep processes in parallel, just do:for i in ${!regex[@]}do        grep -h -r --color=always ${regex[$i]} file.txt >> pattern$i.txt &donewait______________†If the indicesare numerically distinct non-negative integers,you can leave out the declare statement.