Replace last 9 delimeters “,” with “|” in UNIX

Hi Guys,

I want to replace last 9 " , " delimeters with " | " in a file

Example :-

"ashu,pant",3,5,5,7,7,87,8,8,8
"ashu,pant"|3|5|5|7|7|87|8|8|8

Help would be really appreciated.

Thanks guys,

Welcome to the forum.

How far would

sed 's/,/\o001/; s/,/|/g; s/\o001/,/' file
"ashu,pant"|3|5|5|7|7|87|8|8|8

get you?

1 Like

Thanks @RudiC for your quick response
I have 2 sets of records, one is without double quote and other is with double quote

Example:-

abcd,3,5,5,7,7,1,2,3,4
"ashu,pant,something",3,5,5,7,7,8,7,8,8,8

Result :-

abcd|3|5|5|7|7|1|2|3|4
"ashu,pant,something"|3|5|5|7|7|8|7|8|8|8

Try

sed 'h; s/^.*"//; s/,/|/g; x; s/[^"]*$//g; G; s/\n//; ' file
"ashu,pant"|3|5|5|7|7|87|8|8|8
abcd|3|5|5|7|7|1|2|3|4
"ashu,pant,something"|3|5|5|7|7|8|7|8|8|8

The request is for the last 9 delimiters but the posted input and output show that the last line contains 10. That renders the counting of separators unreliable and another requirement must be established, like the double quotes or perhaps when the line reaches a single digit.

Alternatively, try:

awk '{for(i=1; i<=NF; i+=2) gsub(",","|",$i)}1' FS=\" OFS=\" file

Which replaces al commas by vertical bars that are not within double quotes.

1 Like

Using the first coma-digit to delineate the start of section with pipes.
Save as himanshupant.py
Run as python3 himanshupant.py

import re

# substitute the txt file with input filename
with open('himanshupant.txt') as rf:
    for line in rf:
        pivot = re.search(',\d', line).start()
        head = line[:pivot]
        tail = re.sub(',', '|', line[pivot:])
        print("{}{}".format(head, tail))

Output:

abcd|3|5|5|7|7|1|2|3|4
"ashu,pant,something"|3|5|5|7|7|8|7|8|8|8
1 Like

Thanks guys for giving solution.