In the previous post about unix shell we met base shell commands useful during application development. This time I will focus only on one command – grep. Grep command is used to find given string in file or files.
Grep command it’s super easy to use if you want to just find given word (case sensitive) in a given file. Let’s say you want to find word create in your log file called user.log – you would use
grep create user.log
If you want to find create word but this time you want to also find an uppercased version you have to pass
--ignore-case option or
-i which is a shortcut for this option:
grep -i create user.log
This is the moment when the fun comes in – you can also use base regular expressions in your command. So if you want to find word create or creating in your file you may want to use this version
grep creat.* user.log
If you want to find all lines where given file does not exist you have to pass
--invert-match option or
-v shortcut. Using
grep -v create user.log will display all lines where word create does not exist.
Instead of a single file, you may want to search through the whole directory, even nested directories. To achieve this you have to use
-r option and then pass directory name at the end instead of the single filename:
grep -r create some_directory/
You can combine options. Following combination would show lines where there is no word starting with create lowercased or uppercased and it would search through given directory:
grep -i -v create.* /directory_name
If you are wondering when given option starts with double dash and when with single remember this: when option name is longer than one character it requires double dash otherwise you can use a single dash – that’s why all shortcuts start with the single dash. It should be easy to remember.
Now grep some file.. sorry, I mean grab some file and start searching for strings!