Reputation: 305
I have a file which is not "readable" (I mean, you can't open it with a text editor, it's weirdly encoded) but with hexdump
, you can see some readable things.
In this file, there is a date. Let's say "05082019". So when i do a hexdump -C
i see this date, and the hex code associated: 3035303832303139
My goal is to write another file exactly like the first one, but with another date in it.
I've tried a simple sed on that date, like:
sed 's/05082019/04102022/g' myfile > newfile
But, since the file is "weirdly encoded", it seems sed
can't find the date in it. So i've tried with hexdump:
hexdump -ve '1/1 "%.2x"' myfile | sed 's/3035303832303139/3034313032303232/g' > newfile
But that was a bit stupid: it's writing the hex string in newfile, giving it a totally different value.
i've also tried to change directly the file, like that:
cp myfile newfile
hexdump -ve '1/1 "%.2x"' newfile | sed -i 's/3035303832303139/3034313032303232/g'
But here sed -i
is waiting for an input file.
Is there a way to write a file knowing only his hex value? (Or do you have another idea to solve that problem?)
(Note that this should be done in bash script. I'm sorry i can't give any encoded file as example.)
Upvotes: 0
Views: 450
Reputation: 22012
You are almost there. Please try xxd -p
to convert binary file to
ascii representation and xxd -p -r
to do the reverse.
xxd -p myfile | tr -d $'\n' | sed 's/3035303832303139/3034313032303232/g' | xxd -p -r > newfile
will do what you want.
Note that if your file size exceeds line length limitation of sed
(depends on the sed version) the approach above may not work. Then please try a perl
solution as an alternative:
perl -0777 -pe 's/05082019/04102022/' myfile > newfile
Unlike sed
, perl
can natively deal with binary files.
Upvotes: 1
Reputation: 3186
If you use hexdump -C $file
and get 3035303832303139
, then $file MUST contain the plaintext 05082019
with no "special encoding".
We can replicate this file like so:
$ printf "Here are some random words 05082019 around the date" > myfile
You were on the right track, you just added an extra > newfile
. Replacing it inline is then a matter of using sed -i
.
$ sed -i -e 's/05082019/04102022/g' myfile
Note: -e used for compatibility between Macos/GNU sed.
$ cat myfile
Here are some random words 04102022 around the date
Upvotes: 2