Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match some words from file and list all the rows of that matching word? (without regex)

Display the Employee details of all those working in a location which ends with ore in its location name

EmpID:Name:Designation:UnitName:Location:DateofJoining:Salary
1001:Thomson:SE:IVS:Mumbai:10-Feb-1999:60000
1002:Johnson:TE::Bangalore:18-Jun-2000:50000
1003:Jackson:DM:IMS:Hyderabad:23-Apr-1985:90000
1004:BobGL::ETA:Mumbai:05-Jan-2004:55000
1005:Alice:PA:::26-Aug-2014:25000
1006:LilySE:IVS::Bangalore:17-Dec-2015:40000
1007:Kirsten:PM:IMS:Mumbai:26-Aug-2014:45000
1004:BobGL::ETA:Mumbai:05-Jan-2021:55000

Expected output:

1002:Johnson:TE::Bangalore:18-Jun-2000:50000
1006:LilySE:IVS::Bangalore:17-Dec-2015:40000

Here's the code I tried, it's only showing the location but I want full details

cut -d ":" -f4 employee.txt | grep 'ore\>' 

EDIT: SOLVED

grep "`cut -d ":" -f5 employee.txt | grep 'ore\>'`$" employee.txt

got output:

1002:Johnson:TE::Bangalore:18-Jun-2000:50000
1006:LilySE:IVS::Bangalore:17-Dec-2015:40000

Thanks everyone for help :)

like image 757
Babbaranish Avatar asked Dec 01 '22 08:12

Babbaranish


1 Answers

Here a non-regex approach using awk:

awk -F: -v s="ore" '(n=index($5,s)) && (n + length(s)-1) == length($5)' file

1002:Johnson:TE::Bangalore:18-Jun-2000:50000
1006:LilySE:IVS::Bangalore:17-Dec-2015:40000

Details:

  • index($5,s) function finds position of input string ore in fifth column i.e $5 of each line
  • (index($5,s) + length(s)-1) == length($5) check is to ensure that ore is the ending substring of $5

A regex approach would be simpler:

awk -F: -v s="ore" '$5 ~ s "$"' file
like image 121
anubhava Avatar answered Dec 03 '22 22:12

anubhava