简体   繁体   English

sed用括号外的逗号替换

[英]sed to replace comma outside parentheses

I have this partial SQL string. 我有这个部分SQL字符串。

select ID,to_char(ts2date(created_t),'DD-MM-YYYY'),name,segment_code from sometable

Using sed, I tried to replace any comma that reside outside the outmost parentheses with string char '~'. 使用sed,我试图用字符串char'〜'替换位于最外面括号之外的任何逗号。

The desired result would be:- 期望的结果是: -

select ID~to_char(ts2date(created_t),'DD-MM-YYYY')~name~segment_code from sometable

Here is what I tried:- 这是我尝试过的: -

sed '
:a
s/[,]\(.*(\)/~\1/g
s/\().*\)[,]/\1~/g
ta

But the result become:- 但结果变成: -

select ID~to_char(ts2date(created_t)~'DD-MM-YYYY')~name~segment_code from sometable

How can I ignore the comma inside the outmost parentheses? 如何忽略括号内的逗号?

TQ for any answer .. :) 任何答案的TQ .. :)

It's not possible to reach such goal with pure sed regex. 使用纯sed正则表达式无法达到这样的目标。 Correct/incorrect bracketing and its depth cannot be recognized by regular automatas (and therefore it cannot be recognized by regular expressions). 常规自动机无法识别正确/不正确的包围及其深度(因此正则表达式无法识别)。

If you want to reach this with a "regex", you might want to use perl and its look-ahead/look-behind features. 如果您想通过“正则表达式”达到此目的,您可能需要使用perl及其前瞻/后视功能。 Or write a simple loop that checks the bracketing. 或者编写一个检查包围的简单循环。

sed is an excellent tool for simple substitutions on a single line. sed是单行简单替换的绝佳工具。 For any other text manipulation, just use awk: 对于任何其他文本操作,只需使用awk:

$ awk '{
    match($0,/\(.*\)/)

    head = substr($0,1,RSTART-1)
    tail = substr($0,RSTART+RLENGTH)

    gsub(/,/,"~",head)
    gsub(/,/,"~",tail)

    print head substr($0,RSTART,RLENGTH) tail
}' file
select ID~to_char(ts2date(created_t),'DD-MM-YYYY')~name~segment_code from sometable

Couldn't be much more straight forward... 不可能更直接......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM