Home > database >  Find all lines in a file with a certain character at a certain position
Find all lines in a file with a certain character at a certain position

Time:12-24

I want, that my bash script counts the lines of a .txt file, which starts with an '#'.

grep -o "#" $FILE | wc -l

I know how to count all lines with a '#' in it but I dont know how to implement the condition, that the '#' needs to be at the start of the program.

The Input are other bash scripts. I want to count how many comments are in the different bash scripts. Than I want to divide the output with the total numbers of lines in the txt file. So I have a percentage of how many lines of the bash script are comments. Like if I have 10 lines of comments in a 100 lines code, 10% of the code are comments.

I also want to scan these lines starting with a '#' after a certain word like "Hello" and count how many lines having this word. Hope someone can help me there too :).

CodePudding user response:

You can count all the lines that start with a # by doing:

grep -c "^#" $FILE

Or after a certain word (with 0 or more other characters between) by doing:

grep -c "Hello.*#" $FILE
  •  Tags:  
  • bash
  • Related