How to grep for the dollar symbol ($)?

LinuxUnixGrep

Linux Problem Overview


% cat temp
$$$ hello1
$$  hello2
    hello3
##  hello4
    hello5 $$$
% cat temp | grep "$$$"
Illegal variable name.
% cat temp | grep "\$\$\$"
Variable name must contain alphanumeric characters.
%

I want to grep for $$$ and I expect the result to be

% cat temp | grep <what should go here?>
$$$ hello1
    hello5 $$$
%

To differentiate, I have marked the prompt as %.

  • What is the problem here?
  • What should the grep string be?

Linux Solutions


Solution 1 - Linux

The problem is that the shell expands variable names inside double-quoted strings. So for "$$$" it tries to read a variable name starting with the first $.

In single quotes, on the other hand, variables are not expanded. Therefore, '$$$' would work – if it were not for the fact that $ is a special character in regular expressions denoting the line ending. So it needs to be escaped: '\$\$\$'.

Solution 2 - Linux

When you use double quotes " or none use double \: "\\\$\\\$\\\$"

cat t | grep \\\$\\\$\\\$ 

if you use in single quotes ' you may use:

cat t | grep '\$\$\$'

Solution 3 - Linux

$ grep '\$\$\$' temp
$$$ hello1
hello5 $$$

There's a superflous 'cat' in your command.

Solution 4 - Linux

Works for me:

user@host:~$ cat temp | grep '\$\$\$'
$$$ hello1
hello5 $$$
user@host:~$ 

Solution 5 - Linux

How about ^.*[$]{3}.*$

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLazerView Question on Stackoverflow
Solution 1 - LinuxKonrad RudolphView Answer on Stackoverflow
Solution 2 - LinuxGadolinView Answer on Stackoverflow
Solution 3 - LinuxjowiView Answer on Stackoverflow
Solution 4 - LinuxtdammersView Answer on Stackoverflow
Solution 5 - LinuxF.PView Answer on Stackoverflow