4

I have a list of users basically from /etc/group, Id like to basically format that line into one column, I just need the users. So if a field looks like this:

bob,john,jane,sam,joyce

Then I'd like it to look like this

bob
john
jane
sam
joyce

I know how to do the opposite but not this type.

5 Answers 5

4

You can do this with sed:

sed 's/,/\n/g'

This replaces all occurrences of , with a newline. g makes sed replace all the occurrences in a line instead of just the first.

3
  • Ok this worked. But what if I have a list of rows like: group1:x:500:bob,john,jane,sam,joyce group2:x:501:jim,sean,fred,will,thomas How can I get them formatted with some break between the groups?
    – unixpipe
    Sep 4, 2014 at 17:44
  • What output do you expect? Sep 4, 2014 at 18:22
  • You can chain two sed calls together, one that strips everything up to and including last colon, and second one as per the answer.
    – user128580
    Sep 4, 2014 at 18:26
1

To answer using your suggested tags:

bash:

$ IFS=, read -a names <<< "bob,john,jane,sam,joyce"
$ printf "%s\n" "${names[@]}"
bob
john
jane
sam
joyce

awk:

$ echo "bob,john,jane,sam,joyce" | awk -F, -v OFS="\n" '{$1=$1; print}'
bob
john
jane
sam
joyce

The $1=$1 bit is an awk idiom to rewrite the current record using the Output Field Separators, which does not happen unless some field is modified.

0
0

You could do this with a find and replace in vim:

:%s/,/\r/g

See this question...

2
  • I need to use this in a script so I couldnt do it in vim
    – unixpipe
    Sep 4, 2014 at 16:42
  • Any help please
    – unixpipe
    Sep 4, 2014 at 17:20
0

A few options:

tr:

tr ',' '\n' < [input file] > [output file]

tr is a tool that filters its standard input and replaces every occurrence of a character from its first argument with the matching one from the second element, then prints to standard out.

vim/ex (this will work in a script):

vim -c "%s/,/\r/g" -c "wq" [input file]

The -c option tells vim to run the following ex command (same as what you would type after a : when using vim normally).

And someone already beat me to sed.

0

If you would like to use awk (similar to Print all Fields with AWK separated by OFS):

echo "bob,john,jane,sam,joyce" | awk  'BEGIN {FS=","; OFS="\n"} {$1=$1; print $0}'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .