【问题标题】:Reverse Search for Pattern from Specific Line in Bash从 Bash 中的特定行反向搜索模式
【发布时间】:2020-06-12 04:09:18
【问题描述】:

假设我有一个大的 XML 字典,格式如下:

<entry>
<!-- arbitrary amount of lines -->
<head>SomeWord</head>
<!-- arbitrary amount of lines -->
</entry>

假设我知道 SomeWord 在第 3,026,138 行。我想从第 3,026,138 行向后搜索直到&lt;entry&gt;,但我不知道&lt;entry&gt; 和我的目标行之间有多少行。

如果我使用行号而不是模式,This answer 可以正常工作,如下所示

sed '/<entry>/h;//!H;3026138!d;x;q' file

但是,这是一个不太理想的解决方案,因为我认为 sed 从第 0 行开始扫描并在文件中爬行 300 万行。这似乎很浪费,因为我已经知道要在文件的哪个区域工作。总而言之,大约需要半秒钟。

有没有人利用我知道行号这一事实的解决方案,该解决方案使用每个人都已经拥有的普通 Unix/sh 程序(例如 grep、awk、sed 等)?

注意:请不要建议我使用xmllint 之类的东西。它不仅非常慢,而且我还希望这是一个与元格式无关的脚本。

【问题讨论】:

  • 不要对(可变长度)行号进行操作。对文件位置进行操作(从文件开始的字节数),

标签: bash unix sed text-processing xmlstarlet


【解决方案1】:

在这里我尝试了以下操作:

  1. 将entry标记行号保存到单独的文件中
  2. 指定head标签所需的行号
  3. 执行搜索“哪里适合”

输入文件:

someline
someline
<entry>
someline
someline
<head>Here</head>
someline
</entry>
someline
<entry>
someline
<head>Another</head>
someline
someline
someline
</entry>
someline
someline

shell 脚本(可以分开以对给定的 ($1) 行号执行搜索。对文件执行多次搜索或以各种方式使用它(通过不同的方法获取所需的标签,然后将行号提供给搜索脚本执行搜索)

# preparation before doing searches
 ln=12 # line number with desired <head>
 cat input.txt | sed '$a<entry>' | grep -n '^<entry>' | cut -d ':' -f1 > entryl.txt
# doing searches
 t=0
 for x in $(seq $(cat entryl.txt | wc -l)); do
  c=$(cat entryl.txt | head -n $x | tail -n 1)
  if test $t -eq 1; then
   if test $ln -lt $c; then
    echo "<head> tag on line: $ln"
    echo "Previous <entry> found at: $p"
    echo "Next <entry> found at: $c"
    break;
   else
    p=$c
   fi
  else
   if test $ln -gt $c; then
    p=$c; t=1
   fi
  fi
 done

样本输出:

<head> tag on line: 12
Previous <entry> found at: 10
Next <entry> found at: 19

【讨论】:

    【解决方案2】:

    sed 之类的工具的问题在于,当您想要处理整个文件的一大块时,它们一次处理一行。输入ed。下面将打印在第 3026138 行之前找到的带有 &lt;entry&gt; 的第一行到该行之间的所有内容:

    echo "3026138;?<entry>?,.p" | ed -s file
    

    (将当前行设置为第3026138行,打印当前行之前&lt;entry&gt;的第一个匹配到当前行之间的范围。如果要将块保存在另一个文件中,可以使用w foo.txt代替p)。

    使用示例文件和第 3 行的示例:

    $ echo "3;?<entry>?,.p" | ed -s input.txt
    <entry>
    <!-- arbitrary amount of lines -->
    <head>SomeWord</head>
    

    【讨论】:

    • 谢谢!我之前并没有真正考虑过使用行编辑器,我不知道为什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 2019-05-16
    • 2014-12-28
    • 1970-01-01
    • 2019-11-05
    • 2016-12-19
    • 1970-01-01
    相关资源
    最近更新 更多