How to replace one character inside parentheses keep everything else as is

后端 未结 5 1167
北恋
北恋 2021-01-19 06:48

The data looks like this :

There is stuff here (word, word number phrases)
(word number anything, word phrases), even more
...

There is a l

5条回答
  •  一向
    一向 (楼主)
    2021-01-19 07:40

    While @randomir's sed solution dwells on replacing a single comma inside parentheses, there is a way to replace multiple commas inside parentheses with sed, too.

    Here is the code:

    sed '/(/ {:a s/\(([^,()]*\),/\1:/; t a}'
    

    or

    sed '{:a;s/\(([^,()]*\),/\1:/;ta}'
    

    or

    sed -E '{:a;s/(\([^,()]*),/\1:/;ta}'
    

    See an online demo.

    In all cases, the main part is between the curly braces. Here are the details for the POSIX ERE (sed with -E option) pattern:

    • :a;
    • s/(\([^,()]*),/\1:/; - find and capture into Group 1
      • \( - a ( char
      • [^,()]* - zero or more chars other than ,, ( and ) (so, only those commas will be removed that are in between the closest ( and ) chars, not inside (..,.(...,.) - remove ( from the bracket expression to also match in the latter patterns)
      • \1: - and replace with the Group 1 contents + a colon after it
    • ta - loop to :a if there was a match at the preceding iteration.

提交回复
热议问题