背景
1、項目開發中,急需要根據資源路徑res下的檔案,生成如下三種格式的檔案。
格式一:
#define IDR_CEF_0001 101
#define IDR_CEF_0002 102
...
#define IDR_CEF_0122 222
格式二:
{“about.html”, IDR_CEF_0001},
{“addProbe.html”, IDR_CEF_0002},
…
{“img/helpimg/help17.PNG”, IDR_CEF_0122},
格式三:
IDR_CEF_0001 HTML “res\about.html”
IDR_CEF_0002 HTML “res\addProbe.html”
IDR_CEF_0122 HTML “res\img\helpimg\help17.PNG”
【着急情況半手工實作如下】
1.C++實作擷取檔案名稱,輸出到txt文檔中,拷貝到Excel以便按列處理。
2.構造格式一左資料,組合成格式一資料。
3.結合notepad++正規表達式比對,構造格式二、三内容,組合成格式二、三資料。
缺點非常明顯:
1.手動,很容易路徑弄錯,檔案少弄,後期Bug不可評估。
2.耗時也接近3個小時。
3.如果又有新的檔案如(Inner,outer,other)三份資源檔案,需要操作3次。
總之,很傻,很笨。
【Shell腳本實作】
源碼如下:
#! /bin/bash
function read_dir()
{
for file in `ls $1`
do
if [ -d $1"/"$file ]; then
read_dir $1"/"$file
else
echo $1"/"$file
fi
done
}
#output files
touch out_files.txt
read_dir "/home/laoyang/test/res" > out_files.txt
#recurse files
#1.delete the front path /home/laoyang
cat out_files.txt | sed 's/\/home\/laoyang\///g' > out22_files.txt
#get line nums
linenums=`cat out22_files.txt | wc -l`
echo $linenums
#construct format_files.txt
#1.#define IDR_CEF_0001 101
rm -rf format_file1.txt
for((i=1;i<=$linenums;i++))
do
echo "#define IDR_CEF_"${i} $[ 100 + ${i} ] >> format_file1.txt
done
#2. {"about.html", IDR_CEF_0001},
cat out22_files.txt | sed 's/test\/res\///g' > out33_files.txt
awk '{print $2}' format_file1.txt > format_file2_1.txt #IDR_CEF_0001 format
sed 's/$/},/g' format_file2_1.txt > format_file2_2.txt
sed 's/^/{"/g' out33_files.txt > out4_file.txt
sed 's/$/",/g' out4_file.txt > out5_file.txt
paste -d " " out5_file.txt format_file2_2.txt > format_file2.txt
#3.IDR_CEF_0001 HTML "res\\about.html"
rm -rf format_file3_2.txt
for((i=1;i<=$linenums;i++))
do
echo "HTML" >> format_file3_2.txt
done
cat out22_files.txt | sed 's/test\///g' > out44_files.txt
cat out44_files.txt | sed 's#\/#\\\\#g' > out55_files.txt
cat out55_files.txt | sed 's#^#"#g' > out66_files.txt
cat out66_files.txt | sed 's#$#"#g' > out77_files.txt
paste -d " " format_file2_1.txt format_file3_2.txt > format_file3_tmp.txt
paste -d " " format_file3_tmp.txt out77_files.txt > format_file3.txt
mkdir format_rst
mv format_file1.txt format_file2.txt format_file3.txt ./format_rst/
優點:
1.快,不會丢失,有多少檔案就是多少檔案。
2.可以複用,新增檔案或者其他子產品也有類似檔案,直接跑一遍腳本即可。
Shell腳本在文本逐行讀取、按列比對、正則比對有先天的優勢。是以Shell實作是很好的選擇。
如果用C++實作代碼行數會幾百甚至上千,且比對會非常複雜。
作者:銘毅天下
轉載請标明出處,原文位址:
http://blog.csdn.net/laoyang360/article/details/49834859