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

问题描述 投票:0回答:1

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

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

输出应该像:

> offset:filename
linux bash search hex
1个回答
0
投票

我也将使用正则表达式:

文本文件:

$ cat tst.txt 
1234567890x1fgg0x1cfffrr

您可以轻松更改/扩展自己的脚本。

#! /bin/bash
part="$(perl -0pe 's/^((?:(?!0(x|X)[0-9a-fA-F]+).)*)(0(x|X)[0-9a-fA-F]+)(.|\n)*/\1:\3\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 (\1).

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

(.|\n)* = Whatever follows.

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

© www.soinside.com 2019 - 2024. All rights reserved.