The UNIX and Linux Forums  

Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting
Google UNIX.COM



View Single Post in UNIX Forums - Click on the Thread or Permalink to View Entire Thread -->
  #6 (permalink)  
Old 03-08-2007
cfajohnson's Avatar
cfajohnson cfajohnson is offline
Shell programmer, author
 

Join Date: Mar 2007
Location: Toronto, Canada
Posts: 974
Quote:
Originally Posted by michaeltravisuk
Hi,

I'm trying to echo a variable that has values separated by colons, putting each value on a new line. So as an example, a variable I might have would contain:

My name is Earl:My name is Dorothy:My name is Bernard:

And I want the output:

My name is Earl
My name is Dorothy
My name is Bernard

Also, I will be unaware of how many values the colon separated variable will contain (as it is generated by another function), so whatever is used will need to be flexible enough to accommodate any number of values. I'm not very competent in awk, so is there a way this can be done either with awk or with something else?

Also, is it possible to specify a field separator (such as a colon or comma) to the for command?
To answer your last question first: yes, set IFS; see my code below.

You don't need awk:

Code:
var="My name is Earl:My name is Dorothy:My name is Bernard:"
set -f
IFS=:
printf "%s\n" $var
A slower method would be to use tr:

Code:
printf "%s\n" "${var%:}" | tr : '\n'
Reply With Quote