替换命令行脚本中的特定字符



>我在文件中有以下内容

{"Hi","Hello","unix":["five","six"]}

我想只用分号替换方括号内的逗号。不应更改行中的其余逗号。

输出应为

{"Hi","Hello","unix":["five";"six"]}

我试过使用 sed,但它不起作用。下面是我尝试过的命令。请帮忙。

sed 's/:[*,*]/;/'

谢谢

如果您的Input_file与所示示例相同,则以下内容可能会对您有所帮助。

sed 's/([^[]*)([^,]*),(.*)/12;3/g'   Input_file

输出将如下所示。

{"Hi","Hello","unix":["five";"six"]}

编辑:现在也添加解释,它应该仅用于解释目的,应该运行上面的代码仅用于获取输出。

sed 's/([^[]*)([^,]*),(.*)/12;3/g'   Input_file
s               ##is for substitution in sed.
([^[]*)       ##Creating the first memory hold which will have the contents from starting to before first occurrence of [ and will be obtained by 1 later in code.
([^,]*)       ##creating second memory hold which will have everything from [(till where it stopped yesterday) to first occurrence of ,
,               ##Putting , here in the line of Input_file.
(.*)          ##creating third memory hold which will have everything after ,(comma) to till end of current line.
/12;3/g      ##Now mentioning the memory hold by their number 12;3/g so point to be noted here between 2 and 3 have out ;(semi colon) as per OP's request it needed semi colon in place of comma.

Awk 在这里也很有用

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

通过使用 gsub ,可以替换特定字段中所有匹配符号的匹配项

输入文件

{"Hi","Hello","unix":["five","six"]}
{"Hi","Hello","unix":["five","six","seven","eight"]}

输出

{"Hi","Hello","unix":["five";"six"]}
{"Hi","Hello","unix":["five";"six";"seven";"eight"]}

你绝对应该使用 RavinderSingh13 的答案而不是我的答案(鉴于非常复杂的输入,它不太可能破坏或表现出意外行为),但这里有一个不太强大的答案,比他的更容易解释:

sed -r 's/(:[.*),(.*])/1;2/g' test

()是一个捕获组。 您可以看到搜索中有两个。 在替换中,它们被称为 12 . 这允许您将搜索块放回替换表达式中。 -r使()不需要用反斜杠转义。 []是特殊的,需要逃避以进行字面解释。 哦,你想要.**. *是一个glob,在某些地方用于 bash 和其他 shell,但不能单独用于正则表达式。

编辑:/g允许多次更换。

最新更新