【问题标题】:Search string using pdfgrep and format output使用 pdfgrep 搜索字符串并格式化输出
【发布时间】:2016-08-01 12:06:25
【问题描述】:

我正在使用 pdfgrep 在存储在目录中的多个 pdf 中搜索名称并将结果存储在文件中:

pdfgrep -R 'My string' > ../output-file

它打印以下输出:

./file1.pdf:     91   My String                               Just_another_string                   75              53            49            30              57               48                74             69
./file2.pdf:     8    My String                                Just_another_string                                                              40
./file3.pdf:     92 My String                                  Just_another_string                   64              62            76             50           76            88             80             148

我在输出的每一列之间的每一行中都得到了很多不必要的空格。我想重新格式化输出,使这些多个空格减少到每列之间只有一个空格。

有什么办法可以做到吗?提前致谢。

【问题讨论】:

    标签: linux pdf grep formatting output


    【解决方案1】:

    快速而肮脏的方式:使用 awk。假设格式总是这样: (假设你原来的命令是正确的)

    pdfgrep -R 'My string' | awk '{print "$1 $2 $3 $4 $5 $6 $7 $8 $9"}' > ../output-file
    

    基于 cmets 编辑:

    @Inian 的答案更好(因为它处理任意数量的列),但简而言之,我正在做的是告诉 awk 用空格分割输入,然后在每列之间用一个空格将其打印回来。 .. 例如,您可以通过不包括 $1 来跳过第一列,或者通过打印 $4 $3) 来交换第 3 列和第 4 列。

    为了提高效率,如果你想把它推到数据库中,你可能想考虑使用 Python(或 Perl 或 PHP,但快速检查我的个人资料应该显示我的偏好)来实际执行 SQL 导入。 500 个 PDF 并没有真正使我分阶段...我希望您可以摆脱类似的情况:

    pdfgrep -R 'My string' > ../output-file
    

    然后运行一个看起来像这样的python程序:

    import sys
    
    with open("output-file","rt") as f:
       for line in f:
          data = line.split() #now you have an array split by whitespace
          cleanline = " ".join(data) #now each element has a single space between it and the next
          #or you could just stick data directly into the database; details omitted because there are way too many variables here
    

    【讨论】:

    • (请注意,有更聪明的方法,而且上面的方法需要您添加 $10 $11 ...如果您有更多列,还要注意我的字符串将是两列)
    • 有什么优化的方法吗?我可能会将这些值传递给数据库以存储它们并在以后有效地使用。为了给你一个想法,我有 500 多个我可能需要搜索的 pdf。 :)
    • 另外你能解释一下你在做什么吗?我对 awk 完全陌生。
    • Inian 似乎删除了他的答案。但是您的回答在很大程度上也可以达到目的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 2012-07-19
    • 2014-11-06
    相关资源
    最近更新 更多