1

How does one proceed to extract member names from a list like the one below and output them to a new file?

Group-name supernatural 
Members admin, Admin1, John, sam, dean 
Group-id 405

expected out-put of newfile.txt :

admin
Admin1
John
sam
dean
  • It is so far very unclear what your expected output is. What do you want to appear in the new file? Each name in its own line? Should the word 'Members' appear? Edit your quesion and include an example. – Panki Mar 12 at 9:53
3
$ awk '/^Members/ { for (i=2; i<=NF; ++i) { sub(",$", "", $i); print $i } }' file
admin
Admin1
John
sam
dean

This uses awk to look for any line that starts with the string Members. When such a line is found, it iterates over the whitespace-delimited fields of that line, from the second field onwards. Each field has its trailing comma removed (if one exists) before it's printed on its own line.

Redirect the output to a new file if you wish to save it, using

awk ...as above... file >newfile

Using sed:

$ sed -n '/^Members[[:blank:]]*/{ s///; s/,[[:blank:]]*/,/g; y/,/\n/; p; }' file
admin
Admin1
John
sam
dean

This locates the lines starting with the string Members and then deletes this string and any blanks (tabs or spaces) following it. It then removes the blanks after any comma in the remainder of the line and changes the commas into newlines before printing the resulting list.

With GNU sed, you could combine

s/,[[:blank:]]*/,/g; y/,/\n/; p;

into

s/,[[:blank:]]*/\n/gp;
1

You can just try with below command combination of awk and sed

awk '/^Members/{$1=" ";print $0}' filename |sed "s/,/\n/g"| sed -r "s/^\s+//g"

output

admin
Admin1
John
sam
dean
  • I'm uncertain whether sed on NetBSD is able to substitute in a newline like that. GNU sed would be able to, though. – Kusalananda Mar 12 at 17:28
1

Tried with python and it worked fine

#!/usr/bin/python
import re
import subprocess
k=re.compile(r'^Members')
y=open('u.txt','r')
for  i in y:
        if re.search(k,i):
            k=re.sub("Members"," ",i)
            print re.sub(",","\n",k).strip()
praveen@praveen:~$ 

output

admin
 Admin1
 John
 sam
 dean
1
 for member in $(cat /tmp/yourfile.txt | grep Members | cut -d' ' -f2-); do 
          echo $member | cut -d, -f1  
 done

Results:

admin
Admin1
John
sam
dean

And it works if you have more than one 'Members' line in the file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.