[英]awk syntax error in bash. Works fine in zsh
I have written the following script that extracts a number from an rss file. 我编写了以下脚本,该脚本从rss文件中提取数字。
#!/bin/sh
wget -O selic https://conteudo.bcb.gov.br/api/feed/pt-br/PAINEL_INDICADORES/juros
line=$(grep 'dailyratevalue' selic)
index=$(awk -v var=$line 'BEGIN {print index(var, "dailyratevalue") }')
end=$((index+21))
echo $line | cut -c $index-$end | tail -c 4 | tr ',' '.' > selic
In zsh it works perfectly, but i need it to work in bash, too. 在zsh中,它可以完美工作,但我也需要在bash中工作。 I have tried running it on bash but i get the following error 我尝试在bash上运行它,但出现以下错误
awk: cmd. line:1: <content
awk: cmd. line:1: ^ syntax error
The error pattern <content
comes from the line that is being fed as a parameter to awk, which makes no sense to me, since awk is just supposed to get me the position of the pattern i want. 错误模式<content
来自作为awk参数输入的行,这对我来说没有意义,因为awk只是应该让我知道所需模式的位置。
What could this be? 这可能是什么?
index=$(awk -v var="$line" 'BEGIN {print index(var, "dailyratevalue") }')
应该修复它。
awk
can do all of the extra steps. awk
可以完成所有其他步骤。 You can just 你可以
wget -qO - https://conteudo.bcb.gov.br/api/feed/pt-br/PAINEL_INDICADORES/juros | \
awk -F '&[gl]t;' '/dailyratevalue/ {sub(",", ".", $25); print $25;}'
and obtain the value you want. 并获得所需的价值。
This is setting the FS and getting the field you want for the line that matches dailyratevalue
. 这是设置FS并获取与dailyratevalue
匹配的行所需的字段。
@DiegoTorresMilano's answer is probably better overall, but if you want to do it in bash, the main thing you need to do is double-quote your variable references. @DiegoTorresMilano的答案总体上来说可能更好,但是如果您要使用bash进行操作,则主要要做的是将变量引用双引号。 Without double-quotes around them, bash (and most shells other than zsh) splits variables into "words", and also expands anything that looks like a wildcard expression into a list of matching filenames. bash(以及zsh以外的大多数shell)周围没有双引号,它将变量分解为“单词”,并且还将任何类似于通配符表达式的内容扩展为匹配的文件名列表。 You almost never want this, so use double-quotes. 您几乎永远不需要它,因此请使用双引号。 In your case, there are two places they're needed: around $line
here: 在您的情况下,有两个地方需要使用: $line
这里:
index=$(awk -v var="$line" 'BEGIN {print index(var, "dailyratevalue") }')
and here: 和这里:
echo "$line" | cut -c $index-$end | tail -c 4 | tr ',' '.' > selic
Note that you don't need double-quotes around the $( )
expressions, because they're on the right side of an assignment statement, and that isn't subject to word splitting and wildcard expansion. 请注意,您不需要在$( )
表达式两边加上双引号,因为它们位于赋值语句的右侧,并且不受单词拆分和通配符扩展的影响。 If they occurred elsewhere, you'd probably want double-quotes around them too. 如果它们发生在其他地方,您可能也希望在它们周围加上双引号。
BTW, shellcheck.net is really good at pointing out common mistakes like this, so I recommend running your scripts through it (even when they seem to be working correctly). 顺便说一句, shellcheck.net确实善于指出类似这样的常见错误,因此我建议通过它运行脚本(即使它们似乎工作正常)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.