/ / Scrivi alcune "if-statement" - bash, shell, if-statement, grep

Scrivi qualche "istruzione if" - bash, shell, if-statement, grep

Voglio scrivere uno script in "if-statement"

Ci sono molti file .html nella cartella ./simulations/ e scrivi il saldo finale nei file html in questo modo:

"saldo finale: 1000.00000000 (0,00%)"

"saldo finale: 19.21977440 (-98.08%)"

"saldo finale: 1135.80974233 (13,58%)"

Voglio solo trovare "end balance: ....... (...%)"

se il saldo finale è 1000 o inferiore dell'eco "end balance 100 0r lwss", se è maggiore, "bilancio fine eco maggiore di 1000".

come questo:

if [ "$(egrep -n "end balance: [0-9.]" ./simulations/*.html)" -gt 1000 ]; then echo " end balance bigger than 1000 " else echo " end balance less than 1000 " fi

risposte:

0 per risposta № 1

Se fate:

egrep -n "end balance: [0-9.]" <<< "end balance: 1135.80974233 (13.58%)"

Otterrete:

1:end balance: 1135.80974233 (13.58%)

Per confrontare il numero devi avere i numeri a sinistra e a destra, quindi ti suggerisco di seguito un'istruzione if:

if (( $(grep -o "end balance: [0-9]{1,}" ./simulations/*.html | awk "{print $3}") > 1000 ))

Se vuoi farlo per ogni file in ./simulation/ usi un loop:

IFS=$"n"
for i in "$( ls -1 ./simulations/ | grep html$ )"
do
if (( $(grep -o "end balance: [0-9]{1,}" "$i" | awk "{print $3}") > 1000 ))
then
echo "end balance bigger than 1000"
else
echo "end balance less than 1000"
fi
done

Sotto il comando:

grep -o "end balance: [0-9]{1,}" <<< "end balance: 1135.80974233 (13.58%)" | awk "{print $3}

Stampa ora: 1135


0 per risposta № 2

La tua condizione fallisce perché l'output della sostituzione del comando non è un numero intero. Inoltre, non viene applicato in base al file.

Nel meta-codice, quello che stai cercando è probabilmente più sulla falsariga di:

for every HTML file, loop
Check the balance at the end of the file.
If it"s greater than 1000, do one thing,
Otherwise, do something else.
end loop

In bash con grep, questo potrebbe assomigliare a:

for f in simulations/*.html; do
if egrep -q "end balance: (1000|[0-9]{3})>" "$f"; then
echo "$f: end balance > 1000"
else
echo "$f: end balance <= 1000 or missing"
fi
done

Se si desidera estrarre il numero dal file per numerico confronto invece di usare un regex, allora potrebbe funzionare:

for f in simulations/*.html; do
n="$(egrep -o "end balance: [0-9]+" "$f" | grep -o "[0-9]*")"
if [[ -z "$n" ]]; then
echo "$f: no balance found"
elif [[ $n -gt 1000 ]]; then
echo "$f: end balance > 1000"
else
echo "$f: end balance <= 1000"
fi
done

In entrambi i casi, otterrai una riga di output per ogni file HTML che viene elaborato.


0 per risposta № 3

Grazie per i maestri di risposta

EB=$(grep "end balance:" ./simulations/*.html) if [[ $(cut -d. -f1 <<<"$EB" | tr -cd [0-9]) -gt 1000 ]]; then echo "end balance bigger than 1000" else echo "end balance less than 1000" fi

lo uso