0

e.g.

~cat ./temp
1,2,"3,1,2",4,5,"A,2,Csd",xx,a,"s,s,,",,,

After shell parse i want this output:

~parse.sh ./temp
1,2,"3_1_2",4,5,"A_2_Csd",xx,a,"s_s__",,,

i.e. replace all the , with _ in the "..." scope.

Any shell solution will be welcome, awk/sed/perl/other smart thing you can think.

snippet code the shorter the better

hedleyyan
  • 437
  • 3
  • 15

1 Answers1

2

You can use this perl command line that transliterates commas to underscores for each match:

perl -pe's#"[^"]*"#$&=~y/,/_/r#ge' ./temp

$& is the whole match

y/// is the transliteration operator (it can also be written tr///)

the r modifier returns a result string (instead of the number of replaced characters).

the e modifier allows to execute code in the replacement pattern.

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
  • Bravo! thx! Can you explain `$&=~y/,/_/r` this part in detail or get a link about what this syntax meaning? 3Q~ – hedleyyan Apr 08 '20 at 04:02
  • 1
    @hedleyyan: Note that if you have to deal with more complex cases (fields with newlines, escaped quotes), build a simple script with the module Text::CSV. – Casimir et Hippolyte Apr 08 '20 at 04:27