n0n0man
n0n0man

Reputation: 23

Replace spaces with commas except for text inside brackets

I'm trying to replace all my spaces with commas to use my file as a CSV input, here is a sample input:

[Royal Gauntlets of Silvermoon] (1) Senhna 2500g
[Chestguard of the Vanquished Hero] (1) Neithia 3000g
[Chestguard of the Vanquished Hero] (1) Buddafly 3000g

and here is my expected output:

[Royal Gauntlets of Silvermoon],(1),Senhna,2500g,
[Chestguard of the Vanquished Hero],(1),Neithia,3000g,
[Chestguard of the Vanquished Hero],(1),Buddafly,3000g,

tr ' ' ',' <input >output works but replaces my spaces in the brackets as well

I know I can do this with awk but I'm unsure as to how exactly to do it. Thanks!

Upvotes: 0

Views: 258

Answers (3)

karakfa
karakfa

Reputation: 67467

if the first field is the only square brackets, another solution

$ awk -F']' '{gsub(" ",",",$2); print $1 FS $2}' file

[Royal Gauntlets of Silvermoon],(1),Senhna,2500g
[Chestguard of the Vanquished Hero],(1),Neithia,3000g
[Chestguard of the Vanquished Hero],(1),Buddafly,3000g

separate the line at the close square bracket, replace single spaces with comma in the second part and join back.

Upvotes: 2

sseLtaH
sseLtaH

Reputation: 11207

If sed is an option

sed 's/\(\[[^]]*]\|([^)]*)\|[a-z]*\) \|$/\1,/g' file
[Royal Gauntlets of Silvermoon],(1),Senhna,2500g,
[Chestguard of the Vanquished Hero],(1),Neithia,3000g,
[Chestguard of the Vanquished Hero],(1),Buddafly,3000g,

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203229

Using GNU awk for FPAT:

$ awk -v FPAT='[^ ]*|[[][^]]+]' -v OFS=',' '{$1=$1}1' file
[Royal Gauntlets of Silvermoon],(1),Senhna,2500g
[Chestguard of the Vanquished Hero],(1),Neithia,3000g
[Chestguard of the Vanquished Hero],(1),Buddafly,3000g

Upvotes: 2

Related Questions