【问题标题】:How to get data from file with tail and awk如何使用tail和awk从文件中获取数据
【发布时间】:2013-11-28 18:13:34
【问题描述】:

我有一个文件,我想从中获取一些数据。 我正在运行 GNU/Linux。

文件: http://pastebin.com/AXF4SJAm

我运行这个命令来获取数据:

tail -n 1 scan.txt > s.txt | awk '/%/ { print $2 }' s.txt

想要的输出:

/home/gustaf/.cache/mozilla/firefox/mwad0hks.default/startupCache/...[2K

但我得到了这个: [~100.0%] /home/gustaf/.cache/mozilla/firefox/mwad0hks.default/startupCache/...[2K

我应该怎么做才能得到desiand结果?

更多详情:

为了生成文件,我使用这个命令:avgscan --heur /home/gustaf > scan.txt

在运行过程中,我尝试了两种解决方案,结果相同:

/home/gustaf/.mozilla/firefox/mwad0hks.default/ghostery/patterns-...[2K
[~5.1%]

我在 python 脚本中使用 scan.txt。

【问题讨论】:

  • 为我工作。你没有向我们展示什么?
  • 给定文件pastebin.com/AXF4SJAm中的终端转义字符有问题

标签: linux awk tail


【解决方案1】:

管道错了。应该是:

tail -n 1 scan.txt  | awk '/%/ { print $2 }'

你不需要s.txt

【讨论】:

    【解决方案2】:

    你也可以试试

    awk '{ arg=$2 } END {print arg}' scan.txt 
    

    但输出在我的 gnome 终端上不可见(我认为是由于文本末尾的终端转义码..)

    如果您删除最后一部分(点和转义码),例如,您可以在终端上获得可见的输出

    awk '{ arg=$2 } END {sub(/\.\..*$/,"",arg); print arg}' scan.txt
    

    生产

    /home/gustaf/.cache/mozilla/firefox/mwad0hks.default/startupCache/
    

    【讨论】:

    • 我使用您的解决方案时应用程序的输出:/home/gustafh/.mozilla/firefox/mwad0hks.default/cookies.sqlite:/c70
    • 你能检查我们使用的是同一个输入文件吗?我知道你在pastebin.com/AXF4SJAm 提供的文件的最后一行是/home/gustaf/.cache/mozilla/firefox/mwad0hks.default/startupCache/...[2K
    【解决方案3】:

    我已经解决了这个问题。

    之前:

    cmd = "awk '{ arg=$2 } END {sub(/\.\..*$/,arg); print arg}' scan.txt"
    x = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    AvgAPI.lastscanned = x.stdout.read()
    

    现在:

    Line_len = 1200
    SEEK_END = 2
    file = open('scan.txt', "r")
    file.seek(-Line_len, SEEK_END)
    data_scanfile_not_cleaned = str(file.read(Line_len)).split(" ")[1].strip()
    if not data_scanfile_not_cleaned.startswith('/'):
       file.close()
       AvgAPI.lastscanned = ""
       time.sleep(0.1)
    else:
       data_scanfile_re = re.sub(r'[~\s+(\d+)%]','',data_scanfile_not_cleaned)
       data_scanfile_strip = data_scanfile_re.strip("[.]")
       data_scanfile = data_scanfile_strip.strip("[K")
       AvgAPI.lastscanned = data_scanfile
       file.close()
       time.sleep(0.1)
    

    新解决方案存在一些小缺陷,但效果令人满意。

    【讨论】:

      猜你喜欢
      • 2019-04-13
      • 2014-07-28
      • 2012-04-16
      • 2019-07-31
      • 1970-01-01
      • 1970-01-01
      • 2015-12-21
      • 2018-06-06
      • 1970-01-01
      相关资源
      最近更新 更多