我想計算從 1 到 4321 范圍內數字“5”出現了多少次。例如,數字 5 出現 1 或數字 555、5 出現 3 次等。
到目前為止,這是我的代碼,但是結果是 0,它們應該是 1262。
#!/bin/bash
typeset -i count5=0
for n in {1..4321}; do
echo ${n}
done | \
while read -n1 digit ; do
if [ `echo "${digit}" | grep 5` ] ; then
count5=count5 1
fi
done | echo "${count5}"
Ps 我正在尋找修復我的代碼,以便它可以列印正確的輸出。我不想要完全不同的解決方案或捷徑。
uj5u.com熱心網友回復:
這樣的事情怎么辦
seq 4321 | tr -Cd 5 | wc -c
1262
創建序列,洗掉除5's 之外的所有內容并計算字符數
uj5u.com熱心網友回復:
這里的主要問題是http://mywiki.wooledge.org/BashFAQ/024。只需最少的更改,您的代碼就可以重構為
#!/bin/bash
typeset -i count5=0
for n in {1..4321}; do
echo $n # braces around ${n} provide no benefit
done | # no backslash required here; fix weird indentation
while read -n1 digit ; do
# prefer modern command substitution syntax over backticks
if [ $(echo "${digit}" | grep 5) ] ; then
count5=count5 1
fi
echo "${count5}" # variable will not persist outside subprocess
done | head -n 1 # so instead just print the last one after the loop
洗掉一些常見的反模式后,這減少到
#!/bin/bash
printf '%s\n' {1..4321} |
grep 5 |
wc -l
一種更有效、更優雅的方法是簡單地
printf '%s\n' {1..4321} | grep -c 5
uj5u.com熱心網友回復:
一個主要問題:
- 每次將結果發送到管道時,所述管道都會啟動一個新的子外殼;當子shell退出時,子shell中設定的
bash任何變數都會“丟失”;最終結果是,即使您在count5子外殼中正確遞增,當您退出子外殼時,您仍然會得到0(起始值)
對 OP 的當前代碼進行最小的更改:
while read -n1 digit ; do
if [ `echo "${digit}" | grep 5` ]; then
count5=count5 1
fi
done < <(for n in {1..4321}; do echo ${n}; done)
echo "${count5}"
注意:這種編碼方法存在一些與性能相關的問題,但由于 OP 已明確要求 a)“修復”當前代碼,并且 b)不提供任何快捷方式......我們將把性能修復留到另一天。 ..
uj5u.com熱心網友回復:
獲取某個數字的更簡單方法n是
nx=${n//[^5]/} # Remove all non-5 characters
count5=${#nx} # Calculate the length of what is left
uj5u.com熱心網友回復:
嘗試rq(https://github.com/fuyuncat/rquery/releases)
seq生成范圍內的數字,countstr計算數字中有多少5。
[ rquery]$ seq 4321 | ./rq -q "s @raw, countstr(@raw,'5')"
...
3650 1
3651 1
3652 1
3653 1
3654 1
3655 2
3656 1
3657 1
3658 1
3659 1
3660 0
3661 0
...
uj5u.com熱心網友回復:
一個更簡單的純方法bash可能是:
printf -v seq '%s' {1..4321} # print the sequence into the variable seq
fives=${seq//[!5]} # delete all characters but 5s
count5=${#fives} # length of the string is the count of 5s
echo $count5 # print it
或者,使用標準實用程式tr和wc
printf '%s' {1..4321} | tr -dc 5 | wc -c
uj5u.com熱心網友回復:
或使用awk:
awk 'BEGIN { for(i=1;i<=4321;i ) {$0=i; x=x gsub("5",""); } print x} '
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/525705.html
標籤:重击脚本
