user2854333
user2854333

Reputation: 640

If string is preceded by comma insert a new line Unix

I have data in below format in a file.

abc : 123456 ,abc : 98766543,xyz : ABC DEF IJK,OPR : No
abc : 456363738,xyz :MNORET ,OPR : YES
abc : 66898965 ,abc : ABC9543,xyz : qwert,OPR : Yes

If abc : is preceded by comma then insert a new line. So that output appears in below format .

abc : 123456 ,
abc : 98766543,xyz : ABC DEF IJK,OPR : No
abc : 456363738,xyz :MNORET ,OPR : YES
abc : 66898965 ,
abc : ABC9543,xyz : qwert,OPR : Yes

I tried using sed to replace it but it is not working . sed -e 's/,abc ://\n abc :/g' 1.txt

Any help is appreciated.

Regards.

Upvotes: 1

Views: 94

Answers (3)

Akshay Hegde
Akshay Hegde

Reputation: 16997

  1. Using awk, gsub() function replace ,abc with ,\nabc

    $ awk '{gsub(/,abc/,",\nabc")}1' infile
    
  2. Using GNU awk gensub() function

    $ awk '{print gensub(/(,)(abc)/,"\\1\n\\2","")}' infile
    

Test Results:

Input:

$ cat infile
abc : 123456 ,abc : 98766543,xyz : ABC DEF IJK,OPR : No
abc : 456363738,xyz :MNORET ,OPR : YES
abc : 66898965 ,abc : ABC9543,xyz : qwert,OPR : Yes

Using awk

$ awk '{gsub(/,abc/,",\nabc")}1' infile
abc : 123456 ,
abc : 98766543,xyz : ABC DEF IJK,OPR : No
abc : 456363738,xyz :MNORET ,OPR : YES
abc : 66898965 ,
abc : ABC9543,xyz : qwert,OPR : Yes

Using GNU awk

$ awk '{print gensub(/(,)(abc)/,"\\1\n\\2","")}' infile
abc : 123456 ,
abc : 98766543,xyz : ABC DEF IJK,OPR : No
abc : 456363738,xyz :MNORET ,OPR : YES
abc : 66898965 ,
abc : ABC9543,xyz : qwert,OPR : Yes

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133438

Following awk solution may also help you in same.

awk '{sub(/,abc :/,",\n&");sub(",\n,",",\n")} 1'   Input_file

Output will be as follows.

abc : 123456 ,
abc : 98766543,xyz : ABC DEF IJK,OPR : No
abc : 456363738,xyz :MNORET ,OPR : YES
abc : 66898965 ,
abc : ABC9543,xyz : qwert,OPR : Yes

Upvotes: 1

Cyrus
Cyrus

Reputation: 88583

With GNU sed:

sed -E 's/(,)(abc :)/\1\n\2/g' file

Output:

abc : 123456 ,
abc : 98766543,xyz : ABC DEF IJK,OPR : No
abc : 456363738,xyz :MNORET ,OPR : YES
abc : 66898965 ,
abc : ABC9543,xyz : qwert,OPR : Yes

Upvotes: 1

Related Questions