Tuesday, 8 December 2015

How to Play With GREP Switches In Unix/Linux

Before proceeding with this article please go through with previous post Basics of GREP Command if you have not read it.

Input File: F_Data_File.txt

EMPID|EMPNAME|EMPDEPT|EMPSAL|LOCATION
10001|A1|HR|10000|USA
10002|A2|FIN|20000|USA
10003|A3|NSS|30000|IND
10004|A4|SEC|40000|USA
10005|A5|TECH|50000|IND
10006|A6|TECH|60000|IND
10007|A7|TECH|70000|IND

1. How to print all the lines which have "TEC" ( independent of case). 

    $ grep -i -w "tec" F_Data_File.txt
    (or)
    $ grep -iw "tec" F_Data_File.txt

    Output: Will not return anything as file doesn't have tec/TEC.

    $ grep -i -w "tech" F_Data_File.txt
    (or)
    $ grep -iw "tech" F_Data_File.txt

    Output: Will return lines which have TECH in it.
     See carefully how switch -i is used in combination with switch -w 

  10005|A5|TECH|50000|IND
  10006|A6|TECH|60000|IND
  10007|A7|TECH|70000|IND

2. How to print all the lines which doesn't have "TECH" ( independent of case).

    $ grep -i -v "tech" F_Data_File.txt
    (or)
    $ grep -iv "tech" F_Data_File.txt

    Output: Will return all the lines which doesn't have TECH in it. 
    See carefully how switch -i is used in combination with switch -v

  10001|A1|HR|10000|USA
  10002|A2|FIN|20000|USA
  10003|A3|NSS|30000|IND
  10004|A4|SEC|40000|USA

3. Search a WORD in all the files under the current directory and its sub directory ( independent of case).

     $ grep -i -w -r "tech"
     (or)
     $ grep -iwr "tech"

Output: Will return lines in all the files in current directory as well as in all the files in subdirectory which contains word TECH.

   F_Input_Data.txt:10005|A5|TECH|50000|IND
   F_Input_Data.txt:10006|A6|TECH|60000|IND
   F_Input_Data.txt:10007|A7|TECH|70000|IND
   test/F_Input_Data.txt:10005|A5|TECH|50000|IND
   test/F_Input_Data.txt:10006|A6|TECH|60000|IND
   test/F_Input_Data.txt:10007|A7|TECH|70000|IND

4. Search all the lines in the files under the current directory and its sub directory ( independent of case) which doesn't have "TECH" in it.
   
   $ grep -i -w -v -r "tech"
(or)
   $ grep -iwvr "tech"
    
Output:Will return lines in all the files in current directory as well as in all the files in subdirectory which doesn't have word TECH.

  F_Input_Data.txt:EMPID|EMPNAME|EMPDEPT|EMPSAL|LOCATION
  F_Input_Data.txt:10001|A1|HR|10000|USA
  F_Input_Data.txt:10002|A2|FIN|20000|USA
  F_Input_Data.txt:10003|A3|NSS|30000|IND
  F_Input_Data.txt:10004|A4|SEC|40000|USA
  test/F_Input_Data.txt:EMPID|EMPNAME|EMPDEPT|EMPSAL|LOCATION
  test/F_Input_Data.txt:10001|A1|HR|10000|USA
  test/F_Input_Data.txt:10002|A2|FIN|20000|USA
  test/F_Input_Data.txt:10003|A3|NSS|30000|IND
  test/F_Input_Data.txt:10004|A4|SEC|40000|USA

Note: Basically, we can use grep switches according to our requirement. It is very simple to use and very effective.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...