sed break into lines (advanced)

Viewed 98

I'm looking to use sed (or combining it with another grep command)to convert the following string

John: Hi!,How are you,?,Dylan: Hey,OK

into

John: Hi!
John: How are you
John: ?
Dylan: Hey
Dylan: OK

If that's not possible I'm willing to compromise for

John: Hi!,How are you,?
Dylan: Hey,OK

Many thanks

5 Answers

In awk:

$ awk 'BEGIN{RS=","}{if($1~/:$/)p=$1;print ($1==p?"":p " ") $0}' file
John: Hi!
John: How are you
John: ?
Dylan: Hey
Dylan: OK

There will be an extra empty line in the end. For some awks (at least GNU awk, mawk and Busybox awk) you can use RS="[,\n]".

sed can be used. There is a great Sed - An Introduction and Tutorial by Bruce Barnett online page, which I always open aside when writing sed script.

Give a try to this:

printf 'John: Hi!,How are you,?,Dylan: Hey,OK\n' | sed -n '
:1
/./ {
  /^[^:,][^:,]*: / {
    h
    s/^\([^:,][^,:]*: \).*$/\1/
    x
    s/,/\n/
    P
    D
  }
  x
  /./ {
    x
    H
    x
    s/\n//g
    x
    s/.//g
    x
    b 1
  }
}'

The output is:

John: Hi!
John: How are you
John: ?
Dylan: Hey
Dylan: OK

With trand awk:

tr ',' '\n' <file | awk '/:/{name=$1; print; next}; {print name,$0}'

or shorter:

tr ',' '\n' <file | awk '/:/?name=$1:$0=name " " $0'

Output:

John: Hi!
John: How are you
John: ?
Dylan: Hey
Dylan: OK

In single awk, considering that your Input_file is same as shown samples then following may help you here.

awk -F',' '
{
  for(i=1;i<=NF;i++){
    if($i~/:/){
      if($i ~ /: /){
        print $i
        split($i,array," ")
        val=array[1]
      }
      else{
        val=$i
      }
    }
    else{
      print val,$i
    }
  }
}'  Input_file

You may try to do something like this:

echo 'John: Hi!,How are you,?,Dylan: Hey,OK' | sed -E "s|(\w+:)|\n\1|g"

It will return:

John: Hi!,How are you,?,
Dylan: Hey,OK
Related