Amith Kotian
Amith Kotian

Reputation: 440

To grep from file to get expected result

I have file contains variable ans with some values defined. i am trying to get all those variables using grep command. i want to list them on basis of "=" sign. i know using grep "ans" Test.txt will list out all the ans variable. but that is not what i am looking for. if i do grep "ans=" Test.txt it should list all variables present with name ans.

Please help me how can i make this work

test.txt

    ans= 10;
    ans =11;
    ans   = 5;
    ans   =    8;

the normal grep command o/p:-

grep ans test.txt

ans= 10;
ans =11;
ans   = 5;
ans   =    8;

Expected grep command o/p:-

grep "ans=" test.txt

ans= 10;
ans =11;
ans   = 5;
ans   =    8;

Upvotes: 1

Views: 134

Answers (2)

Ed Morton
Ed Morton

Reputation: 203229

$ grep 'ans *=' file
    ans= 10;
    ans =11;
    ans   = 5;
    ans   =    8;

If that's not all you need then edit your question to clarify your requirements and provide better sample input/output that can be used to thoroughly test your requirements.

Upvotes: 1

anubhava
anubhava

Reputation: 784998

You may try this awk:

awk -v key='ans=' '
{
   s = $0
   gsub(/[[:blank:]]+/, "", s)
}
s ~ "^" key {
   print
   exit
}' test.txt

    ans= 10;
    ans =11;
    ans   = 5;
    ans   =    8;

Upvotes: 2

Related Questions