Replace nth to nth character?

Hi

I got the following problem and I wonder if some could please help me out?
I'd like to replace character 8 - 16 , 16 - 24

cat file

4040AB50025D8843039E31F70000E5020046904444047FD76A029E8009E8B387C19C7FA44E2842B1D6229383502608435A552D1A5DD33EC7F13EC43F1A67B2B648F2E16D7122D39A89DA8D075644158C70048E5B92C2DECB00EA020051904F44049A16C9312C09E3ED1E0D792E923D1AF2C97FCAE2ED66DB003E505DAC0F09C31D024E10A497301D954F060033CD7C2D96B6729CE3620416FB2405519F70A2E32D86AFF28724D590BF7087557BB6
cat file | sed 's/\(.\{8\}\).\{8\}/\1AAAAAAAA/'

4040AB50AAAAAAAA039E31F70000E5020046904444047FD76A029E8009E8B387C19C7FA44E2842B1D6229383502608435A552D1A5DD33EC7F13EC43F1A67B2B648F2E16D7122D39A89DA8D075644158C70048E5B92C2DECB00EA020051904F44049A16C9312C09E3ED1E0D792E923D1AF2C97FCAE2ED66DB003E505DAC0F09C31D024E10A497301D954F060033CD7C2D96B6729CE3620416FB2405519F70A2E32D86AFF28724D590BF7087557BB6

Works ok and replaces characters, string is the same length

cat file | sed 's/\(.\{16\}\).\{16\}/\1AAAAAAAA/'
4040AB50025D8843AAAAAAAA0046904444047FD76A029E8009E8B387C19C7FA44E2842B1D6229383502608435A552D1A5DD33EC7F13EC43F1A67B2B648F2E16D7122D39A89DA8D075644158C70048E5B92C2DECB00EA020051904F44049A16C9312C09E3ED1E0D792E923D1AF2C97FCAE2ED66DB003E505DAC0F09C31D024E10A497301D954F060033CD7C2D96B6729CE3620416FB2405519F70A2E32D86AFF28724D590BF7087557BB6

Cuts some characters off????

Thanks for your help

sed 's/\(.\{16\}\).\{16\}/\1AAAAAAAA/' file

The cat command is not necessary since sed can read a file on its own.
The red part is matching another 16 characters, and when you \1 those 16 matched chars are discarded and replaced by AAAAAAAA.

sed 's/\(.\{16\}\).\{8\}/\1AAAAAAAA/' file

The red part has to be the same length of the substitution if you do not want to truncate the original line any farther.

---------- Post updated at 05:25 PM ---------- Previous update was at 05:02 PM ----------

You can do it with many other programs, however I prefer Perl.

perl -pe 'substr($_, 16, length "AAAAAAAA") = "AAAAAAAA"' file

4040AB50025D8843AAAAAAAA0000E5020046904444047FD76A029E8009E8B387C19C7FA44E2842B1D6229383502608435A552D1A5D...
1 Like

Thank you very much all worked great :wink: