用逗号替换空格,括号内的文本除外
Replace spaces with commas except for text inside brackets
我正在尝试用逗号替换我的所有空格以将我的文件用作 CSV 输入,这是一个示例输入:
[Royal Gauntlets of Silvermoon] (1) Senhna 2500g
[Chestguard of the Vanquished Hero] (1) Neithia 3000g
[Chestguard of the Vanquished Hero] (1) Buddafly 3000g
这是我的预期输出:
[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
有效,但也替换了括号中的空格
我知道我可以用 awk 做到这一点,但我不确定具体怎么做。
谢谢!
使用 GNU awk FPAT
:
$ awk -v FPAT='[^ ]*|[[][^]]+]' -v OFS=',' '{=}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
如果sed
是一个选项
sed 's/\(\[[^]]*]\|([^)]*)\|[a-z]*\) \|$/,/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,
如果第一个字段是唯一的方括号,另一种解决方案
$ awk -F']' '{gsub(" ",",",); print FS }' file
[Royal Gauntlets of Silvermoon],(1),Senhna,2500g
[Chestguard of the Vanquished Hero],(1),Neithia,3000g
[Chestguard of the Vanquished Hero],(1),Buddafly,3000g
在右方括号处分隔行,在第二部分用逗号替换单个空格并重新连接。
我正在尝试用逗号替换我的所有空格以将我的文件用作 CSV 输入,这是一个示例输入:
[Royal Gauntlets of Silvermoon] (1) Senhna 2500g
[Chestguard of the Vanquished Hero] (1) Neithia 3000g
[Chestguard of the Vanquished Hero] (1) Buddafly 3000g
这是我的预期输出:
[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
有效,但也替换了括号中的空格
我知道我可以用 awk 做到这一点,但我不确定具体怎么做。 谢谢!
使用 GNU awk FPAT
:
$ awk -v FPAT='[^ ]*|[[][^]]+]' -v OFS=',' '{=}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
如果sed
是一个选项
sed 's/\(\[[^]]*]\|([^)]*)\|[a-z]*\) \|$/,/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,
如果第一个字段是唯一的方括号,另一种解决方案
$ awk -F']' '{gsub(" ",",",); print FS }' file
[Royal Gauntlets of Silvermoon],(1),Senhna,2500g
[Chestguard of the Vanquished Hero],(1),Neithia,3000g
[Chestguard of the Vanquished Hero],(1),Buddafly,3000g
在右方括号处分隔行,在第二部分用逗号替换单个空格并重新连接。