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.
CodePudding user response:
Use the pipe symbol (|
) to connect multiple grep
, indirectly realize the and
matching of multiple keywords.
num_line=$(grep "^ *#" a.txt | grep -cw "exit")
CodePudding user response:
Count all lines that start with #
and contain exit
$ grep -c '^#.*exit' input_file
CodePudding user response:
try grep "^#(.*)?exit(.*)?$" a.txt
?