How to replace one character in parentheses, everything else, like

The data is as follows:

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

There are a lot of them in different files. There are different types of data, all around which are not in the same format. The data inside the parades cannot change, and they are always on the same line. I do not need to deal:

(stuff number,
maybe more here)

I would like to be able to replace the comma with a colon

The desired conclusion will be

There is stuff here (word: word number phrases)
(word number anything: word phrases), even more
...
+4
source share
5 answers

Assuming that only one comma is replaced in parentheses, this POSIX BRE expression sedwill replace it with a colon:

sed 's/(\(.*\),\(.*\))/(\1:\2)/g' file

If there is more than one comma, only the last will be replaced.

In a multi-comma scenario, you can only replace the first:

sed 's/(\([^,]*\),\([^)]*\))/(\1:\2)/g' file
+4
source

awk, :

awk -v RS='[()]' 'NR%2 == 0 {sub(/,/,":")} {printf "%s%s", $0, RT}' file

. RT , RS .

, . , gsub sub

+4

@randomir sed , sed.

:

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

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

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

-.

. POSIX ERE (sed -E):

  • :a;
  • s/(\([^,()]*),/\1:/; - 1
    • \( - a ( char
    • [^,()]* - , ,, ( ) ( , ( ), (..,.(...,.) - ( , )
    • \1: - 1 +
  • ta - loop to :a, .
+2

awk

$ awk -v FS="" -v OFS="" '{ c=0; for(i=1; i<=NF; i++){ if( $i=="(" || $i ==")" ) c=1-c; if(c==1 && $i==",") $i=":" } }1' file
There is stuff here (word: word number phrases)
(word number anything: word phrases), even more

-v FS="" -v OFS="" FS null, char .

set a variable c=0. Iterate over each field using a loop forand toggle the values cif (or occurs ).
if there is c==1, and ,then replace it with a:

+1
source

WITH perl

$ perl -pe 's/\([^()]+\)/$&=~s|,|:|gr/ge' ip.txt
There is stuff here (word: word number phrases)
(word number anything: word phrases), even more

$ echo 'i,j,k (a,b,c) bar (1,2)' | perl -pe 's/\([^()]+\)/$&=~s|,|:|gr/ge'
i,j,k (a:b:c) bar (1:2)

$ # since only single character is changed, can also use tr
$ echo 'i,j,k (a,b,c) bar (1,2)' | perl -pe 's/\([^()]+\)/$&=~tr|,|:|r/ge'
i,j,k (a:b:c) bar (1:2)
  • e modified allows you to use perl code in the replacement section
  • \([^()]+\)matches non-nested ()with one or more characters inside
  • $&=~s|,|:|grmake another substitution in the agreed text, the modifier rwill return the changed text
+1
source

Source: https://habr.com/ru/post/1688637/


All Articles