Script to find and grep the group

59 views Asked by At

I am struggling to write a bash script or python script to find a string from a file.

For example, I need to search for usrname4 and if it found then I need fetch its group. In this case, it is group1. Since the file format is tricky i am looking after some hints.

The file contents are in below format.

group1    (-,usrname1,abc.co.uk)\
          (-,usrname1,xyz.co.uk)\
          (-,usrname2,abc.co.uk)\
          (-,usrname2,xyz.co.uk)\
          (-,usrname3,abc.co.uk)\
          (-,usrname3,xyz.co.uk)\
          (-,usrname4,abc.co.uk)\
          (-,usrname4,xyz.co.uk)\
          (-,usrname5,abc.co.uk)\
          (-,usrname5,xyz.co.uk)\
          (-,usrname6,abc.co.uk)\
          (-,usrname6,xyz.co.uk)\
          (-,usrname7,abc.co.uk)\
          (-,usrname7,xyz.co.uk)\
group2    (-,usrname8,abc.co.uk)\
          (-,usrname8,xyz.co.uk)\
          (-,usrname9,abc.co.uk)\
          (-,usrname9,xyz.co.uk)\
          (-,usrname10,abc.co.uk)\
          (-,usrname10,xyz.co.uk)\
          (-,usrname11,abc.co.uk)\
          (-,usrname11,xyz.co.uk)\
          (-,usrname12,abc.co.uk)\
          (-,usrname12,xyz.co.uk)\
          (-,usrname13,abc.co.uk)\
          (-,usrname13,xyz.co.uk)\
          (-,usrname14,abc.co.uk)\
          (-,usrname14,xyz.co.uk)\
1

There are 1 answers

2
Walter A On BEST ANSWER

I added the following specifications:

  • A group can be found by looking for the a line that starts without a space
  • A group name is without spaces
  • When username occurs more than once, only look at the first one
  • Search for the last group mentioned before the match

First select all groups and all matched lines.
From that set look for the last line before the first match, that must be the group.

usr=usrname4
grep -Eo "^[^ ]+|,${usr}," file | grep -B1 ",${usr}," | head -1