Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm having a String which is seperated by commas like a,b,c,d,e,f that I want to split into an array with the comma as seperator. Then I want to print each element on a new line. The problem I'm having is that all cli tools I know so far(sed, awk, grep) only work on lines, but how do I get a string into a format that can be used by these tools. What i'v tried so far is

echo "a,b,c,d,e,f" | awk -F', ' '{print $i"\n"}'

How can I get this output

a
b
c
d
e
f

from this input

a,b,c,d,e,f

?

share|improve this question
    
I'm not clear what you're really asking. You can translate commas to newlines with "tr": echo a, b, c, d | tr , '\n' -- that leaves spaces at the start of the b/c/d lines. – glenn jackman Feb 2 at 20:54
    
IFS=',' read -a array <<<"a,b,c,d,e,f" ; printf '%s\n' "${array[@]} – Costas Feb 2 at 21:03
    
@glennjackman tr -s ', ' '\n' – Costas Feb 2 at 21:15
    
line="a,b,c,d,e,f" ; echo -e ${line//,/\\n} – Costas Feb 2 at 21:19
    
@Costas, hmm, what if there's a space within a field? tr -s ', ' '\n' will split the field into multiple lines. – glenn jackman Feb 2 at 21:50
up vote 1 down vote accepted

Sticking with your awk ... just make sure you understand the difference between a field and a record separator :}

echo "a,b,c,d,e,f" | awk 'BEGIN{RS=","}{$1=$1}1'

But the tr solution in the comments is preferable.

share|improve this answer
1  
What's with the $i? – iruvar Feb 2 at 21:46
    
good question; purious (from OPs incantation). will delete :) – tink Feb 2 at 21:47
1  
awk '{$1=$1}1' RS=, looks shorter with trailing \newline removed – Costas Feb 2 at 22:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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