What Does Grep -v '^#' Do

What Does Grep -v '^#' Do

My program looks like this.

ALL=`cat $1 | grep -v '^#' | wc -l`
FINISHED="0"

for i in `cat $1 | grep -v '^#'`; do
        echo "PROBE $i"
 I will be doing some operation
FINISHED=`echo $FINISHED"+1"|bc`

I will run this script by giving a file name as parameter where a list of probes will be present.

I have 2 questions

  1. What does grep -v '^#' mean. I learnt that '^ is usually used to matching a particular string. But in the file name which I give there is no #. Moreover I am getting the total number of probes for cat $1 | grep -v '^#' | wc -l.

  2. echo $FINISHED"+1"|bc. Here any idea as to why the developer as added |bc?

2

3 Answers

  • ^ means "start of line"
  • # is the literal character #
  • -v means "invert the match" in grep, in other words, return all non matching lines.

Put those together, and your expression is "select all lines that do not begin with #"

| is the pipe character, it takes the output of the command on the left hand side, and uses it as the input of the command on the right hand side. bc is like a command line calculator (to do basic math).

2

I would use this to exclude comments from the code I'm reading. So all comment lines start with # and I don't want to see them if there are too many of them.

grep -v '^#'

We have different ways for calculation. Pick the one which you like.

a=`echo 1+1 | bc`; echo $a
b=$((1+1)); echo $b
c=`expr 1 + 1`; echo $c
let d=1+1; echo $d

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.