-4

I want to grep the exact string 'CAAJ' from a file "aaa.log" and it following contents.

cat aaa.log

CAAJ:dd20gf:acldx009:rel7

CAAJ:dd20gi:acldx009:rel7

CAAJ:dd20gp:acldx0059:rel7

CAAJ-TEST:de27ff:acldx003:rel7

CAAJ-TEST:de27ei:acldx003:rel7

CAAJ-TEST:de27ep:acldx003:rel7

Expected Output:

CAAJ:dd20gf:acldx009:rel7

CAAJ:dd20gi:acldx009:rel7

CAAJ:dd20gp:acldx0059:rel7

I am trying the following code.And i get the O/p.

grep -E '(^|)CAAJ(:|$)' aaa.log

CAAJ:dd20gf:acldx009:rel7

CAAJ:dd20gi:acldx009:rel7

CAAJ:dd20gp:acldx0059:rel7

But when I use a Variable instead of the exact string I am unable to get the O/p

var=CAAJ

grep -E '(^|)${var}(:|$)' aaa.log

OR 

grep -E '(^|)"${var}"(:|$)' aaa.log

None of these worked.

I want to use the variable instead of the exact string and get the desired o/p

0

Try this:

var=CAAJ;grep "^$var:" aaa.log;
1

try this..

awk -F: '$1=="CAAJ" aaa.log

using variable in awk

awk -F: -vv="$var" '$1==v' aaa.log

grep command

grep "^$var:" aaa.log
1

First of all, I have no idea what you think the parentheses are doing, but there is no reason at all to use (^|). That means "start of the string, or nothing." I'm surprised it's valid syntax.

Likewise, (:|$) seems senseless when all of the occurrences you care about occur at the start of the string.

If you put a variable in double quotes it will expand. If you put it in single quotes it won't.

You don't need extended regex for any of this.


Instead of:

grep -E '(^|)'${var}'(:|$)'

Use:

grep ^CAAJ: aaa.log

Or:

var=CAAJ
grep "^${var}:" aaa.log

Or, since the field delimiter you care about is :, just use Awk:

awk -F: '$1 == "CAAJ"' aaa.log

Note that in this last case, the single quotes are for the shell and the double quotes are for Awk. Everything inside of the single quotes, including $1, will be passed to Awk exactly as it is.

0

I played around with the ' and it worked.

grep -E '(^|)'${var}'(:|$)' 
-2

try

grep -E "(^|)${var}(:|$)" aaa.log

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.