【问题标题】:Use sed to extract ascii hex string from a file使用 sed 从文件中提取 ascii 十六进制字符串
【发布时间】:2014-08-05 18:39:39
【问题描述】:

我有一个如下所示的文件:

$ some random
$ text
00ab2c3f03$ and more
random text
1a2bf04$ more text
blah blah

还有如下代码:

sed -ne 's/\(.*\)$ and.*/\1/p'  "file.txt" > "output1.txt"
sed -ne 's/\(.*\)$ more.*/\1/p' "file.txt" > "output2.txt"

这给了我这个00ab2c3f03 和这个1a2bf04

因此它会从行首提取到shell prompt 的任何内容并将其存储在文件中,两次用于两个不同的实例。

问题是文件有时看起来像这样:

/dir # some random
/dir # text
00ab2c3f03/dir # and more
random text
345fabd0067234234/dir # more text
blah blah

我想制作一个通用提取器:

  • 从行首提取数据到“$”或“/”字符
  • 智能提取随机数量的随机hex从行首到第一个non-hex数字

但我不太擅长 sed 自己想出一个简单的解决方案...

【问题讨论】:

    标签: bash shell sed hex ascii


    【解决方案1】:

    我想你想要这样的输出,

    $ cat file
    $ some random
    $ text
    00ab2c3f03$ and more
    random text
    1a2bf04$ more text
    blah blah
    /dir # some random
    /dir # text
    00ab2c3f03/dir # and more
    random text
    345fabd0067234234/dir # more text
    blah blah
    
    $ sed -ne 's/\([a-f0-9]*\).* and more.*/\1/p' file
    00ab2c3f03
    00ab2c3f03
    
    $ sed -ne 's/\([a-f0-9]*\).* more text.*/\1/p' file
    1a2bf04
    345fabd0067234234
    

    你也可以试试下面的 GNU sed 命令。因为/ 出现在您的输入中,所以我将sed 分隔符更改为~

    $ sed -nr 's~([a-f0-9]*)\/*\$*.* and more.*~\1~p' file
    00ab2c3f03
    00ab2c3f03
    
    $ sed -nr 's~([a-f0-9]*)\/*\$*.* more text.*~\1~p' file
    1a2bf04
    345fabd0067234234
    

    解释:

    • ([a-f0-9]*) - 捕获所有十六进制数字并将其存储到一个组中。

    • OP 说可能有/$ 符号出现在十六进制数字之后,因此正则表达式应该是\/*\$*(/ 零次或多次,$ 零次或多次次)在捕获组之后。

    • 第一个命令仅适用于包含字符串 and more 的行。

    • 第二个仅适用于包含 more text 的行,因为 op 想要两个不同文件中的两个输出。

    【讨论】:

    • 谢谢你的解释,现在我想请你帮忙解决非常相似的问题:文件中只有一行只包含十六进制字符,我该如何提取?我试过sed -ne 's/^\([A-F0-9]*\)$/\1/p' file我使用行首和行尾(^&)作为分隔符,但我显然遗漏了一些东西......
    【解决方案2】:

    这对我来说似乎更好:

    sed -nr 's#([[:xdigit:]]+)[$/].*#\1#p' file
    

    【讨论】:

      猜你喜欢
      • 2014-08-06
      • 1970-01-01
      • 2011-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 2013-02-07
      相关资源
      最近更新 更多