I have this tricky text block where some ending quotes appear on the next line. I want to replace every comma appearing between quotes with @ symbol.

"----, ----",, ----, ----,,"",start quote," starting
 next line with end quote, ",---,, "--- ,", "begin quote ,,
,,nxt line end quote ",----, ----",, ----, "----,,"---","",
---- ,","----, ----",,"", --",--,----,,,

I can do it with sed if it wasn't for that tricky end quote on next line but having trouble doing it with perl.

  • 1
    Can the quotes be escaped? Can you include the expected output for the input so we can test our solutions? – choroba Apr 4 '18 at 11:37
  • Interesting. Even though this is essentially a CSV file, csvformat from CSVkit gets it wrong and does not properly quote the second line-spanning quote. – Kusalananda Apr 4 '18 at 12:06
  • Ah, I see why csvformat gets it wrong. One of the quoted fields on the second line starts with a space before the quote. The field is therefore not strictly quoted, but contains a quote character. – Kusalananda Apr 4 '18 at 12:13
  • in worst case, i could replace all new line characters with a temporary character so the whole thing becomes one line and then use the sed script i have to replace the commas, and then replace the temporary chars with \n again. but im not sure if that is efficient if i have a 100k rows file with 20 columns. What you recon? – Harry McKenzie Apr 4 '18 at 12:45

If the quotes can't be nested nor escaped, just split the input on quotes, modify each odd element, and join back with quotes:

use warnings;
use strict;

my $input = '"----, ----",, ----, ----,,"",start quote," starting
 next line with end quote, ",---,, "--- ,", "begin quote ,,
,,nxt line end quote ",----, ----",, ----, "----,,"---","",
---- ,","----, ----",,"", --",--,----,,,';

my @segments = split /"/, $input;  # fix SO syntax highlighting: "
s/,/@/g for @segments[ grep $_ % 2, 0 .. $#segments ];
print join '"', @segments;
| improve this answer | |
  • hi choroba! thank you very much for your input ! really appreciate it ! – Harry McKenzie Apr 4 '18 at 13:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.