21

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.

  • 5
    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
35

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
  • 3
    Note that using \n in the replacement string like that will work in GNU sed, but will fail in most other sed implementations. – wjv Nov 4 '16 at 12:10
  • @chrisdown Is there a way to get the first two to work in AIX? – cokedude Oct 23 '19 at 22:49
4
$ line=foo:bar:baz:quux
$ words=$(IFS=:; set -- $line; printf "%s\n" "$@")
$ echo "$words"
foo
bar
baz
quux
4

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
  • 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
0

don't know why ppl hate on xargs

$ xargs --version | head -1
xargs (GNU findutils) 4.7.0
...
$ printf "foo:bar:baz:quux" | xargs -d: -n1
foo
bar
baz
quux
-1

In some strings I had problem with solutions above. But this worked for me:

echo $string | sed 's/\\n/ /g' | tr " " \\n
  • As written, this does not transform the OP example input. – kbulgrien Mar 29 '18 at 15:48

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.