Search code examples
sedregexp-replace

sed: find and replace nth character in a line that starts with a specific string


I have a couple thousand files with the same line formatting. I am trying to replace the 17th character (a letter) in every line that begins with a string (the word "ATOM"), without changing anything else in the file. So for example, I'd like to replace the 17th character after the word ATOM from "D" to "A":

INPUT

ATOM 14632 2HG2 VAL D 923 56.949 47.137 72.598 1.00 0.00 H

OUTPUT

ATOM 14632 2HG2 VAL A 923 56.949 47.137 72.598 1.00 0.00 H

I'm using the following code, which changes the letter, but deletes everything before it in that line:

sed -i '.bak' 's/^\(ATOM.\{17\}\)D/\A/' input.file

OUTPUT

A 923 56.949 47.137 72.598 1.00 0.00 H

Any help on what I'm doing wrong here would be greatly appreciated.

The '.bak' is there since I'm on a Mac.


Solution

  • It's:

    sed 's/^\(ATOM.\{16\}\)D/\1A/'
    
    • .\{16\} - You said I'd like to replace the 17th character after the word ATOM from "D" to "A". So you want to match any 16 characters and then match the 17th character that is a D.
    • \1 - put what is remembered with the first \(...\) there.
    • A - followed by an A.