I have a bash file processing some CSVs. Some of the input CSVs are not formatted properly, so I want to fix them with sed. The quotes are escaped like \" and not like "", so I call sed to change this. In the command line this works perfectly:
sed -i 's/\\"/""/gi' input.csv
But inside a bash script this seems to do nothing. I guess it has something to do with quotes and escape sequences, but what is the solution?
you need to escape the escape character
\for that to work:for bash scripts, you need to make sure that the line you read from the CSV file is properly quoted when passing it to sed. Can you provide an example of the CSV file as well as how you read from the file?
Using
cat file | while read, here is an example of the problem:One solution is to not use echo in the script but use sed directly on the file and storing the resulting csv in a new file:
Then, as pointed into the comments, to avoid clobbering and wrong replacements of quoted fields finishing by
\, we can use 2 sed expressions, and include the field separator to ensure we replace only the\"preceding or following the field separator (in my example, the field separator is;) but this one doesn’t take into account fields single quoted with a\as last character in the field such as thebloline:If you have several sed command, you can put the in a script, it works the same way:
Using it: