Home > OS >  Replace the matched string in the comma separated string pattern
Replace the matched string in the comma separated string pattern

Time:06-22

I have a comma separated strings inside brackets and I need to replace the string in matches the pattern. And we have unknown string at the start and at the end. In the below example I need to replace c string with c if the row has string ruby. I tried below sed command but it didnt work.

```
("java","php","ruby",".net","scala","c  ",...n),
(".net","ruby","php","java","c  ",...n),
("java",".net","ruby","php","c  ",...n),
("ruby","java",".net","php","c  ",...n);
```

```
sed -e "s/(\(.*\),\("ruby"\),\(.*\),"c  ",\(.*\))/(\1,\2,\3,"c",\4)/g"
```

CodePudding user response:

("java","php","ruby",".net","scala","c  ",...n),
(".net","ruby","php","java","c  ",...n),
("java",".net","ruby","php","c  ",...n),
("ruby","java",".net","php","c  ",...n);

'

{m,n,g}awk '/\42ruby\42/ ? NF = NF : NF' FS='"c[ ][ ]"' OFS='"c"'

'

("java","php","ruby",".net","scala","c",...n),
(".net","ruby","php","java","c",...n),
("java",".net","ruby","php","c",...n),
("ruby","java",".net","php","c",...n);

CodePudding user response:

it seems like your sed command is not escaping double quotes

sed -e "s/(\(.*\),\("ruby"\),\(.*\),"c  ",\(.*\))/(\1,\2,\3,"c",\4)/g"

change it to single quotes.

sed -e 's/(\(.*\),\("ruby"\),\(.*\),"c  ",\(.*\))/(\1,\2,\3,"c",\4)/g' file.txt

or more simply use the below one...

sed -e 's/\("ruby"\),\(.*\),"c  "/\1,\2,"c"/g' my_file.txt

which will output

("jsjs","java",".net","php","c  ",...n);
("java","php","ruby",".net","scala","c",...n),
(".net","ruby","php","java","c",...n),
("java",".net","ruby","php","c",...n),
("ruby","java",".net","php","c",...n);
("rubys","java",".net","php","c  ",...n);
  • Related