1830207 Members
1996 Online
109999 Solutions
New Discussion

Sed to remove comma

 
Aravind_3
Frequent Advisor

Sed to remove comma

How do I sed

Group1::101:user1,users,user3,user4,user4
to
Group::101:

The following command
sed -e 's/'$username'//' -e '/,$//' /etc/group
not working

Here's the output
Group1:::101:,,,,


Thanks
Aravind
8 REPLIES 8
Stefan Farrelly
Honored Contributor

Re: Sed to remove comma


cat /etc/group|sed 's/:/ /g'|sed 's/,/ /g'|awk '{print $1"::"$2":"}'
Im from Palmerston North, New Zealand, but somehow ended up in London...
H.Merijn Brand (procura
Honored Contributor

Re: Sed to remove comma

grep [,:]$username /etc/group | cut -d: -f1,3
Enjoy, Have FUN! H.Merijn
curt larson_1
Honored Contributor

Re: Sed to remove comma

how about:
sed 's/\(.*:\).*/\1/'/etc/group
Darrell Allen
Honored Contributor

Re: Sed to remove comma

Hi,

First, presuming you mean to delete one command from the end of the line, it appears your second expression should be:
-e 's/,$//'

I assume you are executing this in a loop and passing a different value for $username each time. If so, you have 4 possible cases (assume $username = user1):
1) $username is the only user in the group
Group1:::101:user1
2) $username is the first of several users in the group
Group1:::101:user1,user2,user3
3) $username is the last of several users in the group
Group1:::101:user3,user2,user1
4) $username is neither first nor last of several users in the group
Group1:::101:user2,user1,user3

Your sed statement needs to allow for each possibility. One method would be:
sed -e 's/'$username'//' -e 's/:,/:/' -e 's/,$//' -e 's/,,/,/' /etc/group

Darrell
"What, Me Worry?" - Alfred E. Neuman (Mad Magazine)
Darrell Allen
Honored Contributor

Re: Sed to remove comma

I've a typo in my first sentence. It should read "delete one comma" instead of "delete one command".

Darrell
"What, Me Worry?" - Alfred E. Neuman (Mad Magazine)
harry d brown jr
Honored Contributor

Re: Sed to remove comma

I have a couple of sed ways:

sed "s/^\(.*\)\:\:\(.*\)\:.*$/\1::\2:/"

or

sed "s/^\(.*\)\(\:.*$\)/\1:/"

both produce

# export OLINE="Group1::101:user1,users,user3,user4,user4"
# echo $OLINE | sed "s/^\(.*\)\(\:.*$\)/\1:/"
Group1::101:
# echo $OLINE | sed "s/^\(.*\)\:\:\(.*\)\:.*$/\1::\2:/"
Group1::101:
#

live free or die
harry
Live Free or Die
F. X. de Montgolfier
Valued Contributor

Re: Sed to remove comma

Errr...

have you tried putting the comma after the username you want to remove?

sed -e 's/'$username'[,]*//' /etc/group

should remove the comma if it exists, and work when there is no comma...

Cheers,

Fran??ois-Xavier
Robin Wakefield
Honored Contributor

Re: Sed to remove comma

...or even:

sed 's/:[^:]*$/:/' /etc/group

Rgds, Robin