2012-04-30 156 views
1

我需要最後3個字符說002,並減少它1 001。我目前有一個問題,它將它轉換爲一個int。所以001變成1.我試圖做的是使用printf並將其轉換回001.然而,這似乎不適用於我。我有以下幾點:零填充Bash/Shell

set -x 

substring() 
{ 
    VAR=$1 
    OFFSET=$2 
    LENGTH=$3 
    RET_VAL=${VAR:$OFFSET:$LENGTH} 
} 

# $1 filename 

# Change to PF Gazetteer directory 
cd $CARRIER_PF_UPDATES_DIR 

LOG=log.txt 
DownloadedFile=$1 
OldFile= 
DATE=$(date +"%Y-%m-%d-%H:%M:%S") 
RET=0 

if [ "${2+1}" == "1" ] 
then 
    echo "Date: " $DATE > $LOG 
    echo "filename: " $DownloadedFile >> $LOG 
fi 

substring ${DownloadedFile} -3 3 
extension=$RET_VAL 
old_ext=$((${extension}+1)) 

substring ${DownloadedFile} 0 9 
echo $RET_VAL 
oldFile="${RET_VAL}${old_ext}" 
oldFile= `printf "%020d" ${RET_VAL}` 
oldFile="${oldFile}.${old_ext}" 

#printf '%03d\n' 1 

echo $oldFile 

# move any temporary files if they exist 
mv "${DownloadedFile}~" ${DownloadedFile} 

# check to see if we got a file 
result=$(grep 226 run.ilog) 


if [ "${2+1}" == "1" ] 
then 
    echo "grep found: " $result >> $LOG 
fi 

if [ -e "${DownloadedFile}" ] 
then 
    #add back onto filename 
    #store back onto var = $OldFile 
    #Check if OldFile exist 
    #Cat files together and - Cat oldFile DownloadedFile > tempFile 
echo "" 
fi 

if [ "$result" == "" ] 
then 
    # File not found 
    RET=100 
else 
    RET=10 
    # START F4202 
    sorted=$(sort -t'+' -k7 ${fileName} > ${fileName}.sorted) 
    if [ -e "${fileName}.sorted" ] 
    then 
     mv "${fileName}" "unsorted/${fileName}.unsorted" 
     mv "${fileName}.sorted" ${fileName} 
    fi 
    # END F4202 
fi 

if [ "${2+1}" == "1" ] 
then 
    echo "script ret: " $RET >> $LOG 
fi 

要查看輸出點擊以下鏈接Ideone我似乎得到1.1而不是1.1的時候我應該得到001

回答

3

這是行不通的:

oldFile= `printf "%020d" ${RET_VAL}` 

刪除後的空間=

+0

這個工程,但現在我得到00000000000000000000.1 – David

+2

那麼這也難怪考慮爲墊 – Hubro

+0

格式化有什麼問題?我仍然是一個初學者,所以請原諒我 – David