AIX Tip of the Week

Search/Replace in vi at a Specific Column

Audience: AIX Users

Date: July 3, 2001

Here's a vi or sed technique to search/replace a string starting at a specific column. We'll start with a simple search, then build to the more complicated search/replace.

To search for the string "abc" starting at column 5, use

/^....abc

The "." matches any character, and the "^" specifies "start at the beginning of the line." For higher column numbers, there's a helpful shorthand notation using braces "{n}".. For example, to search for the string "abc" starting at column 75:

/^.\{74\}abc

The braces match the preceding character "n" times. In this case, match the first n=74 characters, followed by "abc". The braces need to be escaped \{ \} so they won't be included as the search string.

When replacing a string at a specific column position, you need to save the pattern up to the search string. The pattern can be saved using parentheses, which is thereafter referenced as "\1". So to replace "abc" at column 75 with "xyz", the syntax would be:

s/\(^.\{74\}\)abc/\1xyz/


Bruce Spencer,
baspence@us.ibm.com