Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

grep

sed

awk

The data looks like this :

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

There is a lot of them in different files. There is different kind of data too, all around it that isn't in the same format. The data inside the paratheses can't change, and it's always on the same line. I do not have to deal with:

(stuff number,
maybe more here)

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

Desired output would be

There is stuff here (word: word number phrases)
(word number anything: word phrases), even more
...
like image 561
Maxime Roussin-Bélanger Avatar asked Dec 11 '22 09:12

Maxime Roussin-Bélanger


2 Answers

Here's a version for awk that uses the parentheses as record separators:

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

The stuff between parentheses will be every even-numbered record. The RT variable holds the character that matched the RS pattern for this record.

Note that this only replace the first comma of the parenthesized text. If you want to replace all, use gsub in place of sub

like image 78
glenn jackman Avatar answered May 15 '23 04:05

glenn jackman


Assuming there's only one comma to be replaced inside parentheses, this POSIX BRE sed expression will replace it with colon:

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

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

In multiple-commas scenario, you can replace only the first one with:

sed 's/(\([^,]*\),\([^)]*\))/(\1:\2)/g' file
like image 26
randomir Avatar answered May 15 '23 03:05

randomir