Ask Doctor Shell ...
This site uses stylesheets and XHTML1.1. You might want to switch to a modern browser like Firefox, Mozilla, or maybe IE6.

How can I replace the second character on a text file ... ...

My text file looks like this:


and I need to replace the "B" character with "Z" obtaining something like this:


I tried :1,$s/B/Z/g in vi, but that changed other "B" characters as well.

What else could I do?


Your vi command will search from beginning of the line and replace all "B"s by "Z"s - throughout the whole file. Thats exactly what the g flag requests. If you want to change only the second character on each line, whatever character it is, try this:


This remembers the first character of each line (\(.\)) and replaces the first two characters by the first character (\1) followed by a "Z".

If you want to replace the second character only if it is "B", try this:


In the first example, the search expression need not be anchored, because any two characters will match. In the second example, the search must be anchored (^), otherwise the first "B" at any character position from column 2 on will match.

Valid XHTML 1.1! Valid CSS!

@(#) $Id: 0004.shtml,v 1.5 2005/06/24 04:49:45 kdo Exp $