Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 529
Dave Avatar asked Mar 25 '15 08:03

Dave


People also ask

How do I search and replace in Vim?

Basic Find and Replace In Vim, you can find and replace text using the :substitute ( :s ) command. To run commands in Vim, you must be in normal mode, the default mode when starting the editor. To go back to normal mode from any other mode, just press the 'Esc' key.

How do I highlight and replace in Vim?

By pressing ctrl + r in visual mode, you will be prompted to enter text to replace with. Press enter and then confirm each change you agree with y or decline with n .

How do I find and replace every incident of a text string vim?

When you want to search for a string of text and replace it with another string of text, you can use the syntax :[range]s/search/replace/. The range is optional; if you just run :s/search/replace/, it will search only the current line and match only the first occurrence of a term.

What is dollar sign in Vim?

Open ~/.vimrc and check its contents. If you see a line like this: set list. It means, it will display $ in every line to mark the end of line. Either remove it or use :set nolist command in the vi editor.


1 Answers

$ 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
like image 140
paxdiablo Avatar answered Jan 01 '23 02:01

paxdiablo