4

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

?

6
  • 1
    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. Feb 2, 2016 at 20:54
  • IFS=',' read -a array <<<"a,b,c,d,e,f" ; printf '%s\n' "${array[@]}
    – Costas
    Feb 2, 2016 at 21:03
  • @glennjackman tr -s ', ' '\n'
    – Costas
    Feb 2, 2016 at 21:15
  • line="a,b,c,d,e,f" ; echo -e ${line//,/\\n}
    – Costas
    Feb 2, 2016 at 21:19
  • @Costas, hmm, what if there's a space within a field? tr -s ', ' '\n' will split the field into multiple lines. Feb 2, 2016 at 21:50

1 Answer 1

6

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.

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

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.