如何在 linux/unix/bash 脚本中搜索文件中的十六进制内容?

How can i search for an hexadecimal content in a file in a linux/unix/bash script?

我有一个十六进制字符串 s 和一个文件 f,我需要在文件中搜索该字符串的第一次出现,然后将其保存在带有他的偏移量的变量中。我认为正确的方法是将文件转换为十六进制并使用 grep 进行搜索。主要问题是我看到了很多要转换的命令(hexdump、xxd 等),但其中 none 确实有效。有什么建议吗? 我的尝试是这样的:

xxd -plain $f > $f
grep "$s" .

输出应该是这样的:

> offset:filename

我也会为此使用正则表达式:

文本文件:

$ cat tst.txt 
1234567890x1fgg0x1cfffrr

您自己可以轻松 change/extend 的脚本。

#! /bin/bash
part="$(perl -0pe 's/^((?:(?!0(x|X)[0-9a-fA-F]+).)*)(0(x|X)[0-9a-fA-F]+)(.|\n)*/:\n/g;' tst.txt)"
tmp=${part/:0x*/}
tmp=${#tmp}
echo ${part/*:0x/$tmp:0x} # Echoes 123456789:0x1f

正则表达式:

^((?:(?!0x[0-9a-fA-F]+).)*) = Search for the first entry that's a hexadecimal number and create a group of it ().

(0x[0-9a-fA-F]+) = Make a group of the hexadecimal number ().

(.|\n)* = Whatever follows.

请注意,如果您在捕获的十六进制数之前有类似 :0x 的文本,tmp=${part/:0x*/} 可能会导致问题。

没有任何错误处理的第一种方法看起来像

#!/bin/bash

BINFILE=
SEARCHSTRING=

HEXSTRING=$(xxd -p ${BINFILE} | tr -d "\n")
echo "${HEXSTRING}"

echo "Searching ${SEARCHSTRING}"
OFFSET=$(grep -aob ${SEARCHSTRING} <<< ${HEXSTRING} | cut -d ":" -f 1)

echo ${OFFSET}:${BINFILE}

我在这里使用 xxd 因为 Does hexdump respect the endianness of its system?. Please take also note that according How to find a position of a character using grep? grep will return multiple matches, not only the first one. The offset will be counted beginning from 1, not 0. To substract 1 from the variable ${OFFSET} 你可以使用 $((${OFFSET}-1)).

即在系统二进制文件中搜索 "string" ELF (HEX 454c46) 将类似于

./searchHEX.sh /bin/yes 454c46
7f454c460201010000000000000000000...01000000000000000000000000000000
Searching 454c46
2:/bin/yes