Grep
Grep command stands for “global regular expression print”. grep command filters the content of a file which makes our search easy.
grep {search-key-word} {filename}
// search for word lisa in test.txt file grep 'lisa' test.txt
grep -n
The -n option display the line number
grep -n 'lisa' test.txt
grep -v
The -v option displays lines not matching to the specified word.
// search for any word that is not lisa in test.txt file grep -v 'lisa' test.txt
grep -i
The -i option filters output in a case-insensitive way.
grep -i 'lisa' test.txt
grep -w
By default, grep matches the given string/pattern even if it found as a substring in a file. The -w option to grep makes it match only the whole words.
grep -w 'lisa' test.txt
Sed
SED command in UNIX is stands for stream editor and it can perform lot’s of function on file like, searching, find and replace, insertion or deletion. Though most common use of SED command in UNIX is for substitution or for find and replace. By using SED you can edit files even without opening it, which is much quicker way to find and replace something in file, than first opening that file in VI Editor and then changing it.
Replace a string
// replace the word lisa with lisak sed 's/lisa/lisak/' test.txt // To edit every word, we have to use a global replacement 'g' sed 's/lisa/lisak/g' test.txt // replace the second occurence of lisa with lisak sed 's/lisa/lisak/2' test.txt // replace from 2nd occurence to the all occurrences sed 's/lisa/lisak/2g' test.txt // replace lisa with lisak on line 2 sed '2 s/lisa/lisak/' test.txt
Delete lines from a file
sed ‘nd’ {filename}
// delete 3rd line in test.txt sed '3d' test.txt // delete from 3rd to 6th line sed '3,6d' test.txt // delete from 3rd to the last line // sed '3,$d' test.txt