I have a poorly formatted CSV file with carriage returns (\r\n) ending each row of data.
However, some text values, between commas, have new lines (\n). This makes reading the file problematic.
In Vim, how can I replace all "\n" that are alone, not part of "\r\n" with ""?
Example file appearance in Vim:
1,a,b,c^M
2,d,e,f^M
3,g
,h,i^M
4,j,k,l
CodePudding user response:
Your answer focuses on substitution and EOL characters so here is a slightly different way to do it with the same tools:
:%s/\(\w\)\n/\1
Where we…
- search for a "word character" followed by a "newline" character,
- capture the word character,
- and finally replace the match with the capture, effectively removing the newline character.
But substitutions and EOL characters are not the only available angle, here. We could simply consider this as a very simple line joining problem:
:g/^,/-j!
Where we…
- execute a command on every line that starts with a comma,
- the command is
:-join!
, which joins the line above the marked line with the marked line, without a space.
See :help :g
, :help :range
, and :help :join
.
CodePudding user response:
As I couldn't figure out how to do it with non-selection regex, I did the following.
I replaced all "\n" with "":
:%s/\n//
Then replaced all "\g" with "^M":
:%s/\g/^M/
Where ^M is input with Ctrl V, Ctrl M