Dave
Dave

Reputation: 4328

How can I search and replace dollar using vim visual mode

I'm editing a shell to be used as a here document. I want to replace the $ dollar signs with \$. How can I do this when vim uses $ as a line ending.

cat > goodband.txt <<EOF 

function bestband
{
  local JON=$1
  local BON=$2
}

EOF


I want  to replace with 


cat > goodband.txt <<EOF 

function bestband
{
  local JON=\$1
  local BON=\$2
}

EOF

I went into visual mode, highlighted the block and tried :s/$/\$\g. But I highlighted and replaced the line endings.

Upvotes: 6

Views: 7016

Answers (2)

paxdiablo
paxdiablo

Reputation: 882716

$ is a special marker for the end of line. If you want to replace literal $ characters, you need to escape them, such as moving to the start of the JON line and entering:

:.,.+1s/\$/\\$/g

(current line and next).

For affecting the visual selection in the case where it's not so easy to work out the line range, you can just use the '< and '> markers:

:'<,'>s/\$/\\$/g

Upvotes: 9

Dave
Dave

Reputation: 4328

I used this <,'>s/\$/\\\$/g

Upvotes: 0

Related Questions