Bash Scripting: How to patch files? (write a given string in a given position of a file)

强颜欢笑 提交于 2019-12-12 13:09:23

问题


Im writing a script to change the UUID of an NTFS partition (AFAIK, there is none). That means writing 8 bytes from 0x48 to 0x4F (72-79 decimal) of /dev/sdaX (X being the # of my partition).

If I wanted to change it to a random UUID, I could use this:

dd if=/dev/urandom of=/dev/sdaX bs=8 count=1 seek=9 conv=notrunc

Or I could change /dev/urandom to /dev/sdaY to clone the UUID from another partition.

But... what if I want to craft a personalized UUID? I already have it stored (and regex-checked) in a $UUID variable in hexadecimal string format (16 chars), like this:

UUID="2AE2C85D31835048"

I was thinking about this approach:

echo "$UUID" | xxd -r -p | dd of=/dev/sdaX ...

This is just a scratch... im not sure about the exact options to make it work. My question is:

  • Is the echo $var | xxd -r | dd really the best approach?
  • What would be the exact command and options to make it work?

As for the answers, Im also looking for:

  • An explanation of all the options used, and what they do.
  • If possible, an alternative command to test it in a file and/or screen before changing the partition.

I already have an 100-byte dump file called ntfs.bin that i can use for tests and check results using

xxd ntfs.bin

So any solution that provides me a way to check results using xxd in screen so i can compare with original ntfs.bin file would be highly appreciated.

Thanks!


回答1:


Try:

UUID="2AE2C85D31835048"
echo "$UUID" | xxd -r -p | wc -c
echo "$UUID" | xxd -r -p | dd of=file obs=1 oseek=72 conv=block,notrunc cbs=8



回答2:


See here:

Replace chars in file by index

# start at char 20, replace the next 11 chars with '#'
echo '###########' | dd  of=FILENAME seek=20 bs=1 count=11 conv=notrunc


来源:https://stackoverflow.com/questions/5196096/bash-scripting-how-to-patch-files-write-a-given-string-in-a-given-position-of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!