Text File Compare Using diff and grep

Make sure both input files are sorted and UPPERCASE

Lines only in file1.txt

diff -d -i -w file1.txt file2.txt | grep "^[<]" > file1-only.txt

Lines only in file2.txt

diff -d -i -w file1.txt file2.txt | grep "^[>]" > file2-only.txt

Lines common in both files

diff -u -d -i -w file1.txt file2.txt | grep -v "^[-+]" > both-files.txt

Grep with SubString

Refer: https://stackoverflow.com/questions/38270261/how-to-extract-a-string-from-between-two-patterns-in-bash

Looking for parameter between -Dappdynamics.agent.nodeName= and closing space

$ ps aux | grep -i appdynamics | grep -oP '(?<= -Dappdynamics.agent.nodeName=)[^ ]+'

$ grep -oP '(?<= -Dappdynamics.agent.nodeName=)[^ ]+' input.txt

-o tells grep to only output the matching part(s) of each line.

-P activates support for PCREs (Perl-compatible regular expressions), which support look-behind assertions such as (?<= inet:), which allow a sub-expression (inet:, in this case) to participate in matching, without being captured (returned) as part of the matched string. [^ ]+ then simply captures everything after inet: up to the first space char. (character set [^ ] matches any char. that is not (^) a space, and + matches this set 1 or more times).

Grep only certain files

$ grep -ir --include pom.xml "<java.version>"

Refer: https://stackoverflow.com/questions/12516937/grep-but-only-certain-file-extensions

$ grep -r -i --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP email@domain.com

Grep file and include lines around search result

grep -A 1 -i "Search-for-something" /var/lib/jbossas/server/halprdjbs01/log/server.log

6.1 Display N lines after match

-A is the option which prints the specified N lines after the match as shown below.

Syntax:
grep -A <N> "string" FILENAME

The following example prints the matched line, along with the 3 lines after it.

$ grep -A 3 -i "example" demo_text

6.2 Display N lines before match

-B is the option which prints the specified N lines before the match.

Syntax:
grep -B <N> "string" FILENAME

When you had option to show the N lines after match, you have the -B option for the opposite.

$ grep -B 2 "single WORD" demo_text

6.3 Display N lines around match

-C is the option which prints the specified N lines before the match. In some occasion you might want the match to be appeared with the lines from both the side. This options shows N lines in both the side(before & after) of match.

$ grep -C 2 "Example" demo_text

Grep Using Regular Expression Example

Use the following example with Cygwin to "-r" recursively scan "-i" ignoring case "-l" list files and use "-E" regular expression which finds all strings that have a pairing of in JSP files

grep -r -i -l -E 'personal.+information' *.jsp