Split contents of a file using grep with TextWrangler on a Mac (Search and replace)

135 Views Asked by At

The contents of my file are as follows

<categories>Category 1, Category 2, Category 3</categories>

The number of categories varies.

I would like to run a search and replace command using grep pattern that will produce this result:

<categories>
   <category>Category 1</category>
   <category>Category 2</category>
   <category>Category 3</category>
</categories>
1

There are 1 best solutions below

0
user11478140 On

awk solution

{ 
    gsub(/<[\/]?categories>/, "");
    n = split($0, a, ", ");
    printf "<categories>\n";
    for (i = 1; i < n+1; i++) printf "  <category>%s</category>\n", a[i]
    printf "</categories>\n";

 }