Raghu
Raghu

Reputation: 51

print second column value after exact match of variables in file

I have a file list.txt containing data like this

hvar-mp-log.hvams [email protected]
mvar-mp-log.mvams [email protected]
mst-mp-log.mst  [email protected]
pif-mp-log-pif [email protected]

I need to match the string in the list.txt and print the matched string second column data.

if string=mst-mp-log.mst print [email protected]. I can match string like this example

   grep -q "$string" list.txt

how to print matched string mail id. expected output should be like [email protected]

Upvotes: 2

Views: 724

Answers (2)

August Karlstrom
August Karlstrom

Reputation: 11377

Here is a solution using individual commands in a pipe:

$ grep '^mst-mp-log.mst ' list.txt | tr -s ' ' | cut -d ' ' -f 2
[email protected]

Upvotes: 0

jared_mamrot
jared_mamrot

Reputation: 26695

With awk:

string="mst-mp-log.mst"
awk -v var="$string" '$1 == var {print $2}' list.txt

Or, if your grep command is already returning the correct lines, perhaps:

grep -q "$string" list.txt | awk '{print $2}'

Upvotes: 2

Related Questions