alteredstate
alteredstate

Reputation: 55

Need To Use Sed To Change The "Nth" Character Of Pattern

I'm having difficulty piecing together the sed syntax to change the last numeric character of this string: <FITID>1261703816 I have a file with several of those fields that need changed but the numeric portion of the string will always be different. However, the amount of numeric characters will always be the same (10). Basically I just need to change the last character of: <FITID>1261703816 to something like: <FITID>1261703817 on a file that contains several hundred of those fields.

Upvotes: 0

Views: 1070

Answers (1)

John1024
John1024

Reputation: 113864

This command will change the tenth digit after <FITID> to 7:

sed -E 's/([<]FITID[>][[:digit:]]{9})[[:digit:]]/\17/g' file

For example:

$ cat file
words, words, <FITID>1261703816 and more words
$ sed -E 's/([<]FITID[>][[:digit:]]{9})[[:digit:]]/\17/g' file
words, words, <FITID>1261703817 and more words

This requires just a single substitute command. [<]FITID[>] matches <FITID> where we put the angle brackets into square brackets because some seds would otherwise treat them as special. [[:digit:]]{9} matches nine digits. We use [:digit:] in place of 0-9 because it is unicode-safe. These characters are all put in parents, (...), so that, in the replacement text, we can reference them as group \1.

Upvotes: 1

Related Questions