convert lines to comma separated items with tr

If you have output that is separated by new lines, but you really want it formatted into a single line with commas as separators or maybe a space as a separator, just pipe to tr.

Here is a simple example:

kserver:~ patternbuffer$ diskutil list | grep ^/dev
/dev/disk0
/dev/disk1

If we want them separated by spaces, we could do:

kserver:~ patternbuffer$ diskutil list | grep ^/dev | tr '\n' ' '
/dev/disk0 /dev/disk1

Note that there is a newline on the end of the output, so that trailing newline is also translated. So if you don’t want it there, you’ll have to chomp it off. I use sed, but use what you like.

Here is the same as above, but with commas, with sed to remove the trailing comma.

kserver:~ patternbuffer$ diskutil list | grep ^/dev | tr '\n' ',' | sed 's/.$//'
/dev/disk0,/dev/disk1

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s