Grep ~ find within files different combinations

grep & cut


Chaining greps together.

Search for a term in file, then find another term from the first result narrowing down your search even further and then with cut you can set a predifined delmiter with -d, in this case that is a whitespace. cut will in the example below take the first instance and the 17th instance and forward

grep SEARCHTERM file.txt | grep "NEWSSEARCHTERM" | cut -f1,17- -d" "

grep FILENAME_log_2014-09-11 | grep " 500 " | cut -f1,18- -d" " | grep -v "200 -"

grep FILENAME_log_2014-09-11 | grep -i "MySearchTerm" | cut -f1,17- -d" " | grep "allOpen"


Chaining greps can be done indefinetly but will add a perfomance decrease to your search.

# Example 4

grep -P "\[\d+\] (Publish Event:)?(Sent Points)?(Sending Points:)?(Sent Points:)?(Point received)?"


# Example 5

# BSD or GNU grep you can use -B num to set how many lines before the 
# match and -A num for the number of lines after the match.
grep -A 5 -B 3 "Hello"

# If you want the same amount of lines before and after you can use -C num
# or just -3 where 3 is the amount of lines.
grep -C 3 "Hello"


as you see the grep and cuts can be piped (chained) to get the output you want, thats what I call a great way to find what you are looking for!

# Example 6

# BSD or GNU grep you can use -B num to set how many lines before the 
tail -f /var/log/server.log | while read line; do echo "$line" | grep -i "no configuration found" | cut -d" " -f8-10,11,13 ; done


Grep OR Operator

grep 'pattern1\|pattern2' filename


Grep OR Using -E ( extended regexp, adds more functionality to your grep )

grep -E 'pattern1|pattern2' filename

Use multiple -e option with grep for the multiple OR patterns.

Grep -v the NOT operator.

grep -v 'pattern1' filename


If you are trying to find the size of different folders but have a lot of files and folders you get access denied for, you can omit those messages this way:

du -cBM --max-depth=1 2>&1 | grep -v 'denied' | sort -n 


2>&1 means to redirect stderr to stdout.



Posted on: Wednesday 13 January 2016