IT_User
IT_User

Reputation: 779

Replacing grep and sed with single awk command

So I have this line of code that I have been trying to convert to just a single awk command, but have been unsuccessful so far (displays nothing). I am not the most experienced with awk, so I am still working on its uses. If someone could give me some guidance and point out what I am doing wrong it would be greatly appreciated. This one-line command will pull a list of all users, and remove all the unnecessary information around it to display just a list of names.

ipa group-show ipausers | grep "Member users: | sed "s/,//g" |
sed "s/Member users: //g" | sort

I have tried a few different ways, but the latest I have tried is;

ipa group-show | awk '/Member users/ { sub ("Member users: ", "") }'

This displays nothing...

From my understanding, awk is capable of searching, and removing excess text pretty easily, and would be a solid use case for what I am trying to accomplish. I just have not been able to accomplish what I am trying. Leads me to a couple questions... Is replacing both the grep and sed an ideal situation for awk, or should grep and sed be used in this case? And what am I doing wrong with awk (probably a lot I'm sure haha).

Example text from ipa group-show

Group name: ipausers
Description: something something
Member users: user1, user2, user3, user4, user5
Member of group: something something

I would like to display:

user1 user2 user3 user4 user5

Upvotes: 0

Views: 4301

Answers (3)

Benjamin W.
Benjamin W.

Reputation: 52536

You could also reduce it to a single (GNU) sed command:

$ sed -n '/^Member users: /{s///;s/,//gp}' infile
user1 user2 user3 user4 user5

This prevents printing with -n, then acts only lines starting with Member users, then removes that term (s/// repeats and removes the last match) and all commas.

A version that (I think – untested) would work with BSD sed (extra semicolon at the end):

sed -n '/^Member users: /{s///';'s/,//gp;}' infile

Upvotes: 2

Sobrique
Sobrique

Reputation: 53508

I'd probably perl it:

perl -ne 's/.* users: // && print join " ", split /, /'

Strips the leading part of the line, and then 'splits' the rest of the line on `, '

Could add a sort in there easily enough

perl -ne 's/.* users: // && print join " ", sort split /, /' 

Upvotes: 1

hek2mgl
hek2mgl

Reputation: 158270

What about this:

awk -F': ' '/Member users:/{print $2}' file

-F: splits the line into fields delimited by :<space>. Doing so, all user names can be obtained from $2.


Update:

In comments you reminded me that you want to remove the , as well. Sorry, missed that. Based on the above command, you can use gsub() to replace , by space in $2.

awk -F': ' '/Member users:/{gsub(","," ",$2); print $2}' file

Upvotes: 4

Related Questions