这可以在sed中使用吗?
我想替换,在元组开头用[和结束]到|
"platform": "iPhone","report_attrs": {"SKU": "XYZ123","Unit Price": "32.25","Qty": "3"},"screen_flow":["Main","Login"]
"platform": "android","report_attrs": {"SKU": "XYZ123","Unit Price": "32.25","Qty": "3"}
输出:
"platform": "iPhone","report_attrs": {"SKU": "XYZ123","Unit Price": "32.25","Qty": "3"},"screen_flow":["Main"|"Login"]
"platform": "android","report_attrs": {"SKU": "XYZ123","Unit Price": "32.25","Qty": "3"}
如果不可能,我们将不胜感激任何其他解决方案。
谢谢。
答案 0 :(得分:2)
以下perl代码会用,
符号替换[]
括号内的所有|
。
$ perl -pe 's/,(?=[^\[\]]*\])/|/g' file
"platform": "iPhone","report_attrs": {"SKU": "XYZ123","Unit Price": "32.25","Qty": "3"},"screen_flow":["Main"|"Login"]
"platform": "android","report_attrs": {"SKU": "XYZ123","Unit Price": "32.25","Qty": "3"}
要保存所做的更改,
perl -i -pe 's/,(?=[^\[\]]*\])/|/g' file
答案 1 :(得分:1)
这是awk
awk -F"[][]" 'NF>1 {gsub(/,/,"*",$2);$2="["$2"]";sub(/ \[/,"[")}1' file
"platform": "iPhone","report_attrs": {"SKU": "XYZ123","Unit Price": "32.25","Qty": "3"},"screen_flow":["Main"*"Login"]
"platform": "android","report_attrs": {"SKU": "XYZ123","Unit Price": "32.25","Qty": "3"}
答案 2 :(得分:1)
sed ':a
s/\(\[[^][]*\),\([^][]*]\)/\1|\2/
t a' YourFile
posix版本(所以--posix
与gnu sed)
在同一条线上,[]和几个[]之间只需要简单的一对。需要进行此e recursif调用,逐个更改每个单独出现,直到没有更多情况。
答案 3 :(得分:0)
我的解决方案:
$ sed 's/[[]\(.\+\),\(.\+\)[]]/[\1|\2]/g' file
"platform": "iPhone","report_attrs": {"SKU": "XYZ123","Unit Price": "32.25","Qty": "3"},"screen_flow":["Main"|"Login"]
"platform": "android","report_attrs": {"SKU": "XYZ123","Unit Price": "32.25","Qty": "3"}
答案 4 :(得分:0)
下一个perl:
perl -pE 's/\[(.*?),(.*?)\]/[\1|\2]/g' <<EOF
"platform": "iPhone","report_attrs": {"SKU": "XYZ123","Unit Price": "32.25","Qty": "3"},"screen_flow":["Main","Login"]
"platform": "android","report_attrs": {"SKU": "XYZ123","Unit Price": "32.25","Qty": "3"}
EOF
打印:
"platform": "iPhone","report_attrs": {"SKU": "XYZ123","Unit Price": "32.25","Qty": "3"},"screen_flow":["Main"|"Login"]
"platform": "android","report_attrs": {"SKU": "XYZ123","Unit Price": "32.25","Qty": "3"}
答案 5 :(得分:0)
这只是https://stackoverflow.com/a/25350541/1745001讨论的问题的另一个例子。
这应该这样做:
$ awk -F'[][]' -v OFS= 'gsub(/,/,"|",$2){$2="["$2"]"}1' file
"platform": "iPhone","report_attrs": {"SKU": "XYZ123","Unit Price": "32.25","Qty": "3"},"screen_flow":["Main"|"Login"]
"platform": "android","report_attrs": {"SKU": "XYZ123","Unit Price": "32.25","Qty": "3"}