Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

What command can I use to split input like this:

foo:bar:baz:quux

into this?

foo
bar
baz
quux

I'm trying to figure out the cut command but it seems to only work with fixed amounts of input, like "first 1000 characters" or "first 7 fields". I need to work with arbitrarily long input.

share|improve this question
2  
You mean like tr : '\n' < input? –  jw013 Dec 11 '12 at 16:00
    
What shell are you using? bash? –  glenn jackman Dec 11 '12 at 21:00

3 Answers 3

up vote 9 down vote accepted

There are a few options:

  • tr : \\n
  • sed 's/:/\n/g'
  • awk '{ gsub(":", "\n") } 1'

You can also do this in pure bash:

while IFS=: read -ra line; do
    printf '%s\n' "${line[@]}"
done
share|improve this answer

If your grep supports -o you can do it like this:

grep -o '[^:]\+'

Or with awk, setting the record separator to ::

awk -v RS=: 1

Or with GNU cut:

cut -d: --output-delimiter=$'\n' -f1-

Edit

As noted by Chris below, this will leave a trailing newline, this can be avoided if your awk supports specifying RS as a regular expression (tested with GNU awk):

awk -v RS='[:\n]' 1
share|improve this answer
    
Your awk example will leave a (probably undesirable) trailing newline. –  Chris Down Dec 11 '12 at 17:51
    
@ChrisDown: you're right, this can be avoided if RS can be a regular expression. –  Thor Dec 11 '12 at 18:33
$ line=foo:bar:baz:quux
$ words=$(IFS=:; set -- $line; printf "%s\n" "$@")
$ echo "$words"
foo
bar
baz
quux
share|improve this answer

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.