2016-11-11 57 views
2

我是shell腳本初學者,我的代碼有點麻煩。如何使用shell腳本在數組中格式化字符串?

我的目標是有規模控制和我的數組數字格式「MyString的」

#!/bin/bash 
mystring="333,4444,333,333,4444,333,333" 
expectedValue=4 
addLeftZero() { 
     if [ $myCount -eq $expectedValue ] 
     then 
      #the number has the correct size 
     else 
      #this is where I have to prepend "0" until the number has the expected lenght, 
      #for example the number "333" will be "0333" 
     fi 
      #here i have to return the full array with the mods 
    } 
IFS=',' read -ra ADDR <<< "$mystring" 
    for i in "${ADDR[@]}"; do 
     myCount=${#i} 
     addLeftZero $i 
     return $i 
    done 

0333,4444,0333,0333,4444,0333,0333

我用sed命令,但似乎我需要編輯一個文件,不能直接在我的代碼。

我可以使用什麼命令來格式化字符串?我是否正確使用該功能?我有我的變量的可見性嗎?你知道更好的方法來實現我的目標嗎?

在此先感謝!

回答

1

假設你只是想離開墊用零的數字,這可以在一個單一的命令來完成:

$ printf '%04d\n' "${ADDR[@]}" 
0333 
4444 
0333 
0333 
4444 
0333 
0333 

這裏的陣列中的每個數字被傳遞給printf作爲單獨的參數 - 它照顧你的格式。

當然,這是否合適取決於你的計劃如何使用這些數字。

另外,return僅用於指示例程是否成功。因此,它僅支持從0255的值。要從函數或命令輸出某些內容,請使用標準輸出/錯誤。

+0

這....只是...真棒謝謝 –

相關問題