Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing a line in bash

Tags:

bash

parsing

I have a file that has one entry per line. Each line has the following format:

 "group:permissions:users" 

Permissions and users could have more than one value separated by comas like this:

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

I want is to return the following:

yo
el
ella

This is what I have so far:

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

This returns yo,el.ella, How can I make it return one value per line?

like image 282
Alan Featherston Avatar asked Dec 17 '22 09:12

Alan Featherston


2 Answers

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
like image 55
Jay Avatar answered Jan 11 '23 05:01

Jay


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
like image 43
user43983 Avatar answered Jan 11 '23 06:01

user43983