tags:

views:

1372

answers:

2

Hi could you please help me parse the following in bash.

i have a file that has one entry per line, and each line has the following format.

 "group:permissions:users"

where permissions and users could have more than one value separated by comas... like this

 "grp1:create,delete:yo,el,ella"

what i want is to return the following

yo
el
ella

i came up with this..

cat file | grep grp1 -w | cut -f3 -d: | cut -d "," -f 2

This returns "yo,el.ella", any ideas how can i make it return one value per line?

Thanks

+2  A: 

You can use awk, with the -F option to use : as the field separator:

[user@host]$ echo "grp1:create,delete:yo,el,ella" | awk -F ':' '{print $3}'
yo,el,ella

That will get you just the users string, separated by commas. Then you can do whatever you want with that string. If you want to literally print each user one per line, you could use tr to replace the commas with newlines:

[user@host]$ echo "grp1:create,delete:yo,el,ella" | awk -F ':' '{print $3}' | tr ',' '\n'
yo
el
ella
Jay
thank you that will do. it never crossed my ming to use awk.... thanks again
Alan FL
sure thing...it's probably doable with *just* awk, but my awk-fu is severely limited ;)
Jay
haha exactly what i would have answered too. +1
Johannes Schaub - litb
A: 

Here's one way to do it entirely in a shell script. You just need to change IFS to get it to break "words" on the right characters. Note: This will not handle escapes (e.g. "\:" in some file formats) at all.

This is written to allow you to do:

cat file | name-of-script

The script:

#!/bin/bash
while IFS=: read group permissions users; do
  if [ "$group" = "grp1" ]; then
    IFS=,
    set -- $users
    while [ $# -ne 0 ]; do
      echo $1
      shift
    done
  fi
done