Replace \n with \n' '

Viewed 74

I have a file like this:

$ cat t.py 
'a\nb\n'

From within the file, with the cursor positioned on the first line, I would like to use :s/ to get to

'a\n'
'b\n'

How can I do that? I have tried

:s/\\n/\n''

but that ends up with

'a^@''b^@'''
1 Answers

You may use this substitution in vim:

:%s/\(\\n\)\([^']\)/\1'\r'\2/g

Explanation:

  • %s/: Substitution start
  • \(\\n\): Match literal \n and capture in group #1
  • \([^']\): Match a character that is not ' and capture in group #2
  • /\1'\r'\2/: Substitute with back-reference #1 + ' + line-break + ' + back-reference #2

Substitution Result:

'a\n'
'b\n'

Or you can use very magic regex in vim and avoid all the escaping:

%s/\v(\\n)([^'])/\1'\r'\2/g
Related