triple fault
triple fault

Reputation: 14146

Looking for exact match using grep

Suppose that I have a file like this:

tst.txt

fName1 lName1-a  222
fname1 lName1-b 22
fName1 lName1 2

And I want to get the 3rd column only for "fName1 lName1", using this command:

var=`grep -i -w "fName1 lName1" tst.txt`

However this returns me every line that starts with "fName1 lName1", how can I look for the exact match?

Upvotes: 2

Views: 106

Answers (3)

Luka
Luka

Reputation: 1718

Here you go:

#!/bin/bash

var=$(grep -Po '(?<=fName1 lName1 ).+' tst.txt)
echo $var

The trick is to use the o option of the grep command. The P option tells the interpreter to use Perl-compatible regular expression syntax when parsing the pattern.

Upvotes: 2

Laser
Laser

Reputation: 6960

you can try this method:
grep -i -E "^fName1 lName1\s" tst.txt | cut -f3,3- -d ' '
But you must be sure that line starts with fName1 and you have space after lName1.

Upvotes: 0

LiMar
LiMar

Reputation: 2982

var=$(grep "fName1 lName1 " tst.txt |cut -d ' ' -f 3)

Upvotes: 1

Related Questions