Thursday, February 9, 2017

grep command with examples - Part - 1

grep is one of most widely used filter in Unix and Linux operating systems, its very simple to use for beginners unlike advanced filters such as sed and awk, though it is less powerful it still comes with lot of inbuilt options, lets explore this good old friend of every Unix student and professional

i have one file "Beautiful_places.txt" . look what does it contain

Australia, country
United States, country
Canada, country
North America, continent
Europe, continent
Japan, country
Asia, continent
India, country
England, country




I have another file "games_and_sports.txt" with following content -
Trump, cards
Ball, cricket
Queen, chess




Now if you want lines only with word "country" from the file Beautiful_places.txt  use following



To see count of matches use "-c" options



 To exclude lines containing a pattern you can use grep with "-v" option



 To see all the lines containing both capital and lower case "a"  ( to make your search case insensitive ) from the file Beautiful_places.txt, use "-i" option with grep command



sometime you may need to  list files which contains certain pattern , "-l" option of grep command proves really helpful in such cases. See below example only one of the file was listed as only this file contained the your search pattern , 





 also see carefully i have used wild card for the list of files being scanned ( *txt ) , so that all the file ending with "txt" will be scanned for this search

 you may also need to see the line numbers of lines containing your search pattern
grep provides a solution for that too , its "-n" option  ( easy to remember as well :  n for number ☺)



grep has lot of other features , its is used frequently inside Unix shell scripts as well,grep regex is also one of the important topic, i will cover some of the advanced features of grep in my next post, you can visit grep man pages as well, i hope you all really enjoyed this short but useful introduction of grep command ,



if you want learn to Basic Unix Commands in 1 Hour, here is the link

Basic Unix Commands in 1 Hour

if you want learn Unix/Linux Commands in detail, here is the link

Learn Unix/Linux Commands in detail

Also keep visiting my blog to learn more

unixtechworld.blogspot.com



No comments:

Post a Comment