1. 程式人生 > >android多語言專案中字串的移植(bash工具)

android多語言專案中字串的移植(bash工具)

有時候我們會遇到這樣一種情況:

一些字串資源要從原始專案A移植到現在我們開發的專案B中

比如移植app名字

<string name="app_label">Calendar</string>
我們需要做的是:

在新專案對應的語言資源中查詢是否有app_label這個資源。

    有:則檢視新舊資源是否一致

        一致:則什麼也不做

        不一致:刪除舊的,新增新的資源

    沒有:新增新的資源

工作內容很簡單,但是,語言種類可能達到五六十種,移植的資源往往也不是一兩個,所以工作量不可忽視

我覺得這種毫無技術含量的體力活還是交給指令碼處理的好,為此特意寫了個工具,希望能幫助大家提高效率

使用方法:

1.先將需要移植的資源的key統一放到一個文字中,用換行分隔。

比如:

$ cat /home/su1216/string_list 
app_name
button_name
company_name
……

注意:string_list這個檔案如果是在windows下製作的,需要先將它轉換成unix格式,方法如下:

用vi開啟指令碼,修改檔案格式,命令如下
:set ff=unix
然後儲存退出

2.然後執行下面命令即可:

merge_strings android_project_src android_project_dest /home/su1216/string_list

#!/bin/bash
#example
#merge_strings project_src/packages/apps/Settings project_dest/packages/apps/Settings string_list
src_dir="$1"
dest_dir="$2"
string_list="$3"

#確保list檔案中含有\n,如果已經含有\n,那麼不會再增加
sed -i -e '$a\' "$string_list"

regex_with_all_string=""
while read line; do
    regex_with_all_string=$regex_with_all_string"name=\"$line\"|"
done < "$string_list"
regex_with_all_string=${regex_with_all_string%|*}
result_list=`grep -Pr "$regex_with_all_string" $src_dir/res/values*/*.xml`
#echo "grep -Pr '"$regex_with_all_string"' $src_dir/res/values*/*.xml"
if [ -f "results.txt" ]; then
    echo "rm results.txt first please."
    exit
fi
touch results.txt

IFS_OLD=$IFS
IFS=$'\n'
for line in $result_list; do
    echo "${line#*res/}" >> results.txt
done
IFS=$IFS_OLD

make_new_xml_file() {
    local country="$1"
    local folder=${country%/*}
    if [ ! -d "$dest_dir/res/$folder" ]; then
        mkdir "$dest_dir/res/$folder"
    fi
    local xml_path="$dest_dir/res/$country"
    touch "$xml_path"
    echo '<?xml version="1.0" encoding="utf-8"?>' > "$xml_path" #line1
    echo '<resources>' >> "$xml_path" #line2
    echo '</resources>' >> "$xml_path" #line3
}

insert_line() {
#</resources> 插入到這行之前
    local string_file="$1"
    local line="$2"
    local trim_line=`echo $2 | grep -Po '\S.*\S'`
    local name=`echo $trim_line | grep -Po "(?<=name=\").*?(?=\")"`
    local line_no=`grep -n "\b$name\b" "$string_file" | grep -Po "^\d+"`
    #a.檢查是否有這個欄位
    if [ "$line_no" != "" ]; then
        #echo "line_no=$line_no" "$string_file"
        local result=`grep -n "$trim_line" "$string_file"`
        #b.檢查是否能完整匹配。如果不能,則刪除舊的,新增新的
        if [ "$result" = "" ]; then
            echo "sed command :""$line_no""d"
            sed -i "$line_no""d" "$string_file"
            sed -i '/<\/resources>/i\'"$line" "$string_file"
        fi
    else
        sed -i '/<\/resources>/i\'"$line" "$string_file"
    fi
}

#MERGE
while read line; do
    country_new=`echo "$line" | grep -Po "^.*?\.xml"`
    string_file="$dest_dir/res/$country_new"
    line=`echo "$line" | grep -Po "(?<=:).*"`
    if [ ! -f "$string_file" ]; then
        make_new_xml_file "$country_new"
    fi
    #echo "$line"
    insert_line "$string_file" "$line"
done < results.txt

轉貼請保留以下連結

本人blog地址