unix - Change Identical Code Strings in Multiple, Separate Files in One Command
2014-04
How can I change strings of code in multiple HTML documents which are all identical to something else? If I have doc A and code , and is replicated in doc A, doc B, doc C, ..., then how can I get the following:
A code1
B code1
C code1
{THIS IS WHERE A COMMAND IS EXECUTED AND BELOW IS THE RESULT}
A code1
B code2
C code2
N.B. - I put "JavaScript" as a tag because I learned today that you can do this with JavaScript. Something about tag replacement.
You can do this using a simple for loop and the sed
editor. Assuming you are using BASH, the command would be:
for i in *.html; do
sed -i s/'foo bar'/'bar baz'/g $i
done
This will substitute every occurance of the string foo bar
with the string bar baz
in every html file in the current directory.
One feature of Notepad++, which I find really useful and haven't found elsewhere, is the highlighting of other text that is identical to the one currently selected.
Is there something similar possible with vi(m)? (Of course, there is. But how do I achieve it?) That is, any of those:
If I am in Visual Mode and have text selected: Highlight identical text
If I have searched
/foo
, highlight all instances offoo
.If I am at the beginning of a string (series of characters, numbers or underscores), highlight all other matching strings (prefered solution).
The last one is similar to the closing parentheses matching and IMHO the most useful.
Edit: For my second use case, I found a solution (that is, Google found it...):
:set hls
However, the others remain.
For your third requirement,
nnoremap , :mat Error "<C-R><C-W>"<CR>
Put this in your vimrc file..Press comma to highlight all occurrences of the word at cursor.
Also, pressing * or # will highlight all occurrences of the string at cursor when hlsearch is set
edit:
For your first requirement,
vnoremap <silent> , :<C-U>
\let old_reg=getreg('"')<Bar>let old_regtype=getregtype('"')<CR>
\gvy:mat Error "<C-R><C-R>=substitute(
\escape(@", '/".*$^~['), '_s+', '\_s\+', 'g')<CR>"<CR>
\gV:call setreg('"', old_reg, old_regtype)<CR>
Found this here. Modified to your needs.
:help hlsearch
When there is a previous search pattern, highlight all its matches.
so, put
set hlsearch
to your vimrc
For door number three, that is what the # key does. It will also jump to the beginning of the previous string of such. Asterisk(*) does the opposite: jump to the beginning of the next string of such.