【问题标题】:Iterate Over X Lines in Variable (Bash)在变量中迭代 X 行(Bash)
【发布时间】:2015-12-01 17:15:03
【问题描述】:

我正在尝试编写一个简单的脚本来打印网页源代码的前 5 行,然后是页面加载所需的请求时间。目前,我一直在尝试以下方法:

#!/bin/bash
# 进入网站,获取数据

输出=$(curl $1 -s -w "%{time_connect}\n" | (head -n5; tail -n1))
回声“$输出”

但是,在某些页面上,“尾巴”实际上并没有打印出来,这应该是请求的时间,我不知道为什么。

我发现我也可以使用 while 循环来遍历行并打印整个内容,但是有没有办法让我只回显变量的前几行,然后回显该变量的最后一行变量,所以我可以在请求时间之前加上一个标题(例如:请求时间:0.489)

我希望能够将其格式化为:

echo "HTML: $output\n"
echo "请求时间:$requestTime"

谢谢!抱歉,如果这看起来很简单,我对这种语言真的很陌生 :)。对我来说主要的问题是从同一个请求中获取这些数据——执行两个单独的 curl 请求会非常简单。

【问题讨论】:

    标签: bash loops curl printing lines


    【解决方案1】:

    head 可能会读取超过 5 行的输入,以确定它需要输出什么。这意味着您打算传递给tail 的行可能已被使用。使用单个进程(在本例中为awk)来处理所有输出会更安全。

    output=$(curl "$1" -s -w "%{time_connect}\n" | awk 'NR<=5 {print} END {print})
    

    【讨论】:

      【解决方案2】:

      回车把我扔了。试试这个:

      echo "HTML: "
      retn=$'\r'
      
      i=0
      while read item
      do
          item="${item/$retn/}"    # Strip out the carriage-return
      
          if (( i < 5 )); then     # Only display the first 5 lines
              echo "$item"
          fi
      
          (( i++ ))
          requestTime="$item"    # Grab the last line
      
      done < <(curl $1 -s -w "%{time_connect}\n")
      
      requestTime="${requestTime##*\>}"    # Sanitise the last line
      
      echo "Request Time: $requestTime"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-22
        • 1970-01-01
        • 2020-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多