crossing crossing - 3 months ago 12
Linux Question

grep whole line if character on position 1 and stings found in line

Hi i'm trying to combine multiple conditions to grep a line from a file.

Eg.

ASTRING1,B1TEST_NAME,/shared/dir1/dir2/dir3/dir4
ASTRING2,B1TEST_NAME,/shared/dir1/dir2/dir3/dir4
ASTRING3,B1TEST_NAME,/shared/dir1/dir2/dir3/dir4
BSTRING1,B1TEST_NAME,/shared/dir1/dir2/dir3/dir4
BSTRING2,B1TEST_NAME,/shared/dir1/dir2/dir3/dir4
BSTRING3,B1TEST_NAME,/shared/dir1/dir2/dir3/dir4
CSTRING1,B1TEST_NAME,/shared/dir1/dir2/dir3/dir4
CSTRING1,B1TEST_NAME,/shared/dir1/dir2/dir3/dir4
CSTRING3,B1TEST_NAME,/shared/dir1/dir2/dir3/dir4
.
.


I want to output the lines into a file only if "B" on the Position 1 AND the string "B1TEST" after the first "," AND the string "dir3" after the second "," exists.

Is it possible with grep? Or is there a "better" command?

I couldn't find anything similar ...

Thanks

Answer

if your input is column based, you can consider awk. However for this requirement, the following grep line should help:

grep '^B[^,]*,B1TEST[^,]*,.*/dir3/' file

It will give you output:

BSTRING1,B1TEST_NAME,/shared/dir1/dir2/dir3/dir4
BSTRING2,B1TEST_NAME,/shared/dir1/dir2/dir3/dir4
BSTRING3,B1TEST_NAME,/shared/dir1/dir2/dir3/dir4
Comments