Argaros
Argaros

Reputation: 93

Grep counting with 2 requirements

Test sample:

#!/bin/bash

echo "Hello"
exit 1

#exit Lorem Ipsum
#Lorem Ipsum

Hello,

so I want to use grep to count the lines which have a '#' in the beginning and have the word 'exit' in it from a .txt file.

I have the code for count all lines with a '#' in the beginning and also the code to count all lines with the word 'exit':

AllExitStatements=$(grep -c "exit" $FILE)
Commentlines=$(grep -c "^ *#" $FILE)

But I dont know how to combine them to get the lines with a '#' as the first letter in the line and the word 'exit' in the line. The Output should be 1. #exit Lorem Ipsum fullfills both requirements.

Hope someone can help me.

Upvotes: 0

Views: 77

Answers (3)

sseLtaH
sseLtaH

Reputation: 11247

Count all lines that start with # and contain exit

$ grep -c '^#.*exit' input_file

Upvotes: 2

Yuxuan Lu
Yuxuan Lu

Reputation: 421

try grep "^#(.*)?exit(.*)?$" a.txt?

Upvotes: 0

过过招
过过招

Reputation: 4244

Use the pipe symbol (|) to connect multiple grep, indirectly realize the and matching of multiple keywords.

num_line=$(grep "^ *#" a.txt | grep -cw "exit")

Upvotes: 2

Related Questions