【问题标题】:How to Index the Output in function如何在函数中索引输出
【发布时间】:2018-06-30 16:19:11
【问题描述】:

我试过的是

read -p "Enter City In Australia: " city

function getaa {
    curl -s http://localhost:8080/api/examples-services/postcode/$city/ | 
    json_pp | grep -E '"' | cut -d \  -f7-30 | cut -d: -f1 |  tr -d '"' |
    sed '1d'

}

getaa

#read -p "Enter City In Zip :" sub
#curl -s http://localhost:8080/api/examples-services/postcode/$city/ | json_pp | grep -E '"' | cut -d \  -f7-30 | cut -d: -f2 | tr -d '",,,' | sed '1d' | sed -n ${sub}p

而且在我进入一个城市后,我想输出他们的邮政编码

我目前的输出是:

Perth 
Perthville 
Perth Gpo 
North Perth 
Perth East 

我的预期输出是:

1.Perth 
2.Perthville 
3.Perth Gpo 
4.North Perth 
5.Perth East 

【问题讨论】:

  • 为什么不保留一个计数器并输出每个输入城市的当前计数,然后将计数增加1
  • @DavidC.Rankin 先生怎么样?
  • 就简单计数而言,就在您的read 上方的declare -i count=0 某处。然后作为getaa 的第一行添加printf "%d." $((count++))。每次调用getaa,都会在第一个城市之前输出1.,然后在第二个城市之前输出2.,以此类推。
  • @IanJayloGuinto,请在您的帖子中使用 CODE TAGS 发布任何 curl 命令左右的输出,cmets 不适合这样做。
  • -w 增加到您需要的任意位数。 (例如-w 3 for 0-999)您可以在nl(1) - Linux man page查看所有选项

标签: arrays linux bash


【解决方案1】:

如果curl -s http://localhost:8080/api/examples-services/postcode/$city/的输出是:

{
    "result": "OK",
    "message": {
        "East Perth": "WA 6892 (PO Boxes 1-827 & 6002-6892)",
        "North Perth": "WA 6906 (PO Boxes)",
        "Perth": "WA 6848 (GPO Boxes 9000-10000)",
        "Perth Airport": "WA 6105",
        "Perth Bc": "WA 6849 (PO Boxes 8001-8506)",
        "Perth East St Georges Tce": "WA 6832 (PO Boxes 3001-3540)",
        "Perth Gpo": "WA 6000",
        "Perth St Georges Tce": "WA 6831 (PO Boxes 5000-5500)",
        "Perthville": "NSW 2795",
        "South Perth": "WA 6951 (PO Boxes)",
        "South Perth Angelo St": "WA 6151 (PO Boxes)"
    }
 }

您在对 DavidC.Rankin 的评论中发布的那个(截断的 json 被转换为有效的,并在此处漂亮地打印出来以提高可见性)。

在您的 bash 函数中,您使用 json_pp 只是为了从 curl 请求中漂亮地打印您的 json。因此我省略它。 如果你的json很简单,那么followign awk one-liner就可以解决你的问题:

awk -F":" 'BEGIN { RS = "{|}|}}|," } NR > 3 { gsub(/"/, "", $0); print NR-3"."$1 }' message.json

read -p "Enter City In Australia: " city
curl -s http://localhost:8080/api/examples-services/postcode/$city/ | awk -F":" 'BEGIN { RS = "{|}|}}|," } NR > 3 { gsub(/"/, "", $0); print NR-3"."$1 }'

输出:

1.East Perth
2.North Perth
3.Perth
4.Perth Airport
5.Perth Bc
6.Perth East St Georges Tce
7.Perth Gpo
8.Perth St Georges Tce
9.Perthville
10.South Perth
11.South Perth Angelo St

在 awk 中,您可以将默认 (newline character) 记录分隔符 (RS) 更改为任何正则表达式。我们在执行开始时执行此操作,在处理任何输入之前。此外,我们将字段分隔符更改为冒号 (:),注意 -F":" 选项。基于简单的示例输入和提供的正则表达式,我们需要提取3rd line (NR > 3) 之后的记录。 gsub 函数从每条记录中删除双引号 (") 然后我们打印出行号和 1st field ($1) 以句点 (.) 分隔,因为它发布在您预期的输出。行号是记录数内置变量NR的变化值与我们转移处理的数量。

【讨论】:

    【解决方案2】:

    如果您只是想在每行的开头添加行号,请通过以下管道输出:

    cat -n
    

    如果你想格式化行号,sed 可以轻松做到这一点

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-15
      • 1970-01-01
      • 1970-01-01
      • 2011-02-28
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 2022-12-20
      相关资源
      最近更新 更多