Grep command behaving strangely

Hi,

I need to count number of '$' symbol in a file and assign it to a variable.
I am using below command.

grep -c '\$' inputfile

O/p:
10359
Its giving correct o/p but when I am assigning the same to a variable its giving completely different o/p.

ab1=`grep -c '\$' inputfile`
$ echo $ab1
316206

:confused:
Can anybody pls help me on this.

Thanks!

Try:

ab1=$(grep -c '\$' inputfile)

wow its working... thanks.. :slight_smile:
can u pls explain why it ws nt working earlier n the functionality of current one..

If you use backticks you need to use extra escape(s) for the dollar sign, otherwise you are counting linefeeds instead of dollar signs. With the $() construct the extra escapes are not necessary.

1 Like