Log In | Register | April 16, 2024

Share
 

Linux - June 14, 2012

Use grep and regular expressions to analyze text.

Grep is a powerful utility that can be used to parse out and or query files for data. Lets say you wanted to find all of the lines that contained the word Linux in the file test.txt. You could easily do this by typing the following.

grep “Linux” test.txt

Grep by default handles searches case sensitively. To disable it you could add the -i flag as such.

grep -i “Linux” test.txt

The above would return all the lines that contain the word Linux or linux.

You could also search using various metacharacters which would allow you to be more specific with your searches. For instance:

grep “^Linux” test.txt

The above command would output every line that started with the word Linux because we prefixed the search with the ^ character.. You could also throw in the -i flag to run the search case insensitive.

Lets say you wanted to search for lines that ended with the word Linux. You could use the $ character as such.

grep -i “Linux$” test.txt

The above command returns all lines that ended with the word Linux case insensitive.

We can also search based on partial match. For instance, lets say we wanted to find every line that starts with L and ends with x. We could do so by the following.

grep “^L.*x$” test.txt

The above command would find every line that starts with L and ends with x. The .* lets grep know that you are trying to search for 0 or more characters in between the L and x. So if 1 of our lines just had the word Linux. This line would be displayed in the output.

You could also use character classes for your searches to find any line that contains a list of characters. For instance, lets try and find any line that contains the letters L,i,n and the numbers 1, and 2.

grep '[Lin12]' test.txt

The brackets allows you to define a list of characters to search for. You could also search for any lines that have 1 set of letters or another but not both by putting the | symbol in the middle.

grep '[Lin|12]' test.txt

Post By: | FavoriteLoadingAdd to favorites

1 Comments

RHCSA Certification Study Guide | DevBlog.co
Monday, June 25, 2012

[...] Use grep and regular expressions to analyze text [...]

Leave a Comment



Need Help? Ask a Question

Ask anything you want from how to questions to debug. We're here to help.

You Must Be Logged In To Post A Question.

Log In or Register