How to look/grep for special characters in a file in linux bash shell ?

Today in this post, we will look how to search or grep special characters in a file text.

To search special characters in linux, we need to escape them using the backslash character (\).

Special characters in linux bash shell are as follows which are recognized by regular expression(regex).

.*[]^${}\+?|()

 

Searching/grepping special characters


### 1. Create a file with below text
[root@nglinux ]# cat testfile 
## hello, this is comment
## welcome to ngelinux
Tomatoes are 10$
Onion is 15$

### 2. Using grep: Now search all lines with "$" symbol in it.
[root@nglinux ]# cat testfile | grep \\$
Tomatoes are 10$
Onion is 15$

### 3. Using awk: Now search all lines with "$" symbol in it.
[root@nglinux ]# cat testfile | awk '/\$/{print $0}'
Tomatoes are 10$
Onion is 15$
[root@nglinux ]# 

### 4. Using sed: Now search all lines with "$" symbol in it.
[root@nglinux ]# cat testfile | sed -n '/\$/p'
Tomatoes are 10$
Onion is 15$

### 5. Similar to $, we can search lines with special character #.
[root@nglinux ]# cat testfile | sed -n '/\#/p'
## hello, this is comment
## welcome to ngelinux
[root@nglinux ]# 

Similar to $ and #, we need to escape all special characters to prevent our shell to interpret it and search them as it is.

Leave a Reply

avatar
  Subscribe  
Notify of