简体   繁体   中英

awk syntax error in bash. Works fine in zsh

I have written the following script that extracts a number from an rss file.

#!/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. I have tried running it on bash but i get the following error

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.

What could this be?

index=$(awk -v var="$line" 'BEGIN {print index(var, "dailyratevalue") }')

应该修复它。

awk can do all of the extra steps. 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 .

@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. 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. You almost never want this, so use double-quotes. In your case, there are two places they're needed: around $line here:

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM