Mahi.G
Mahi.G

Reputation: 11

sed command to replace char at a specific byte position

I am having two files say test1 & test2 having a difference at some random position.So i want to search for char position that differ in test1 from test 2 & want to replace that with * in test 1 . But the constraint is without knowing the char by just knowing the position of char. So i have tried to use the cmp -b to get the byte position that differ but cant get something in sed or any where that can replace char at a byte position or something in compare that will give line no. as well as char position in line that differ. So any help (the main constraint is that cant replace with char value as don't want that change at other places in file want change only at that position). sed first occurrence replacement will also not work as first occurence may be before the differ position.

Upvotes: 0

Views: 1130

Answers (1)

Roman Khimov
Roman Khimov

Reputation: 4977

So you just want to write some byte at some offset without file truncation, maybe dd will help?

Setup:

$ cat f1
aaaaaaaaaaaaaaaaaaaaaaaaa
$ cat f2
aaaaaaaaaaaaaaabaaaaaaaaa

Script:

if ! CMPOUT=`cmp -b f1 f2`; then
    POS=`echo "$CMPOUT" | sed -r 's/^.*: byte ([0-9]+),.*$/\1/'`
    echo -n '*' | dd of=f2 seek="$((POS-1))" bs=1 count=1 conv=notrunc
fi

Result:

$ cat f2 
aaaaaaaaaaaaaaa*aaaaaaaaa

Upvotes: 1

Related Questions